0

How to set the value of an array from a function? The issue is because I've to change the value of the index before of be set with an variable value.

function foo(arr) {
    this.arr=arr;
}

var f = new foo(['a', 'b', 'c']);

// I had thinked in use a function like this one
// Note thta I used index to pass an array wich could
// be greater than 1 dimension.

foo.prototype.setv = function(index, v) {
    this.arr.index = v;
}

// but it does not works like I was expecting
idx = [1];
foo.setv(idx, "Z");
0

4 Answers 4

3

This:

this.arr.index = v;

Should be this:

this.arr[index] = v;

In your code you are setting a property of the array, named "index" to a value. This does not actually use the index argument passed to your setter function. Using the braket notation for setting allows you to use the index argument as an actual index for the array.

But also, your expected usage is strange:

idx = [1];
foo.setv(idx, "Z");

Why is idx an array? If you want to set a specific index of the internal array to a value, you would expect to pass in just the index. So that would make more sense to be simply:

idx = 1;
foo.setv(idx, "Z");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. IMHO, all Stack Overflow answers should include the why, as well as the how.
1
foo.prototype.setv = function(index, v) {
    this.arr[index] = v;
}

idx = 1;
foo.setv(idx, "Z");

Comments

0
foo.prototype.setv = function(index, v) {
    this.arr[index[0]]= v;
}

Comments

0

There are quite a few mistakes in the code you've posted:

// capitalizing "constructors" is a good standard to follow
function Foo(arr) {
    this.arr = arr;
}

var f = new Foo(['a', 'b', 'c']);

Foo.prototype.setv = function(index, v) {
    // you access array indices via arr[index], not arr.index
    this.arr[index] = v;
}

// idx should be a number, not an array
idx = 1;

// you call the prototype function on the new'd object, not the "class"
f.setv(idx, "Z");

http://jsfiddle.net/2mB28/

Comments

Your Answer

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