0

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 here). 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?

1
  • 3
    why not simply use a[0] = [0,0];? Commented Oct 14, 2011 at 6:44

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.