开发者

In JavaScript, how to return a part of an Array by reference from a method?

开发者 https://www.devze.com 2023-04-12 18:49 出处:网络
I want to extend the Array.prototype to include a method to select a row or a column from a 2x2 matrix (a list of lists in JavaScript jargon). The method should return by Reference the selected Array

I want to extend the Array.prototype to include a method to select a row or a column from a 2x2 matrix (a list of lists in JavaScript jargon). The method should return by Reference the selected Array elements and thus the result can be used to dynamically change certain values in the Array.

the slice() method of Array doesn't return by Reference

a = [[1,2],[3,4]];
a.slice(0,1) = [0,0];

ReferenceError: invalid assignment left-hand side

My failed attempt

Array.prototype.row = function(whichrow) {
var result = this[whichrow];
return result;
}

It works fine when only the values are needed

a.row(0)
[1, 2]

However, apparently it returns only the value of the row instead of the row itself (if I'm making sense her开发者_运维知识库e). So when I try to assign a new value to it, it returns error

a.row(0) = [0,0];
ReferenceError: invalid assignment left-hand side

Anyone has any suggestion?


I'd recommend to implement your row function like this:

Array.prototype.row = function(whichrow, newvalue) {
    if( newvalue !== undefined ) {
        this[whichrow] = newvalue;
    }
    return this[whichrow];
}

and use it like this:

a.row(0, [0,0]);

And retrieving:

a.row(0)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号