如何从函数中将值设置为数组?在JavaScript中

时间:2012-10-19 18:39:39

标签: javascript arrays

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

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 个答案:

答案 0 :(得分:3)

此:

this.arr.index = v;

应该是这样的:

this.arr[index] = v;

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

但是,你的预期用法很奇怪:

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

为什么idx是一个数组?如果要将内部数组的特定索引设置为某个值,则可能只会传入索引。因此,简单来说更有意义:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

答案 3 :(得分: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/