如何通过函数设置数组的值? 问题是因为我必须在设置变量值之前更改索引的值。
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");
最佳答案
这个:
this.arr.index = v;
应该是这样的:
this.arr[index] = v;
在您的代码中,您正在将名为“index”的数组属性设置为一个值。这实际上并没有使用传递给 setter 函数的 index
参数。使用小括号表示法进行设置允许您使用 index
参数作为数组的实际索引。
而且,您的预期用法很奇怪:
idx = [1];
foo.setv(idx, "Z");
为什么idx
是一个数组?如果您想将内部数组的特定索引设置为一个值,您可能希望仅传入该索引。因此,简单地说会更有意义:
idx = 1;
foo.setv(idx, "Z");
关于javascript - 如何从函数将值设置到数组中?在 JavaScript 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980446/