0

如何从函数中设置数组的值?问题是因为我必须在使用变量值设置之前更改索引的值。

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");
4

4 回答 4

3

这:

this.arr.index = v;

应该是这样的:

this.arr[index] = v;

在您的代码中,您正在将名为“index”的数组属性设置为一个值。这实际上并不使用index传递给您的 setter 函数的参数。使用小括号表示法进行设置允许您将index参数用作数组的实际索引。

而且,您的预期用法很奇怪:

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

为什么是idx数组?如果要将内部数组的特定索引设置为一个值,则希望只传入索引。因此,简单地说:

idx = 1;
foo.setv(idx, "Z");
于 2012-10-19T18:41:37.367 回答
1
foo.prototype.setv = function(index, v) {
    this.arr[index] = v;
}

idx = 1;
foo.setv(idx, "Z");
于 2012-10-19T18:41:49.797 回答
0
foo.prototype.setv = function(index, v) {
    this.arr[index[0]]= v;
}
于 2012-10-19T18:41:20.983 回答
0

您发布的代码中有很多错误:

// 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/

于 2012-10-19T18:52:28.073 回答