function foo(a) {
a = a.map(function(x) {return 0;});
}
var A = [1,1,1];
foo(A); //seems like A should now be [0,0,0]
console.log(A); //nope its [still 1,1,1]. debugging shows that the parameter a in foo changes properly to [0,0,0] but does not transfer to A
A = [0,0,0]; //force A to [0,0,0] now
console.log(A);
function bar(a) {
A = A.map(function(x) {return 1;}); //checking if i can force it back to [1,1,1] using this slight change
}
bar(A);
console.log(A); //this works
那么为什么 foo 不起作用呢?
A 被传递到 foo
的参数 a 中,因此 foo 的代码应该 run
为 A = A.map(whatever)
,就像在 bar?
我有一些模糊的猜测,它是 javascript
如何处理 array
pointers
在 assignment
或者其他什么。
最佳答案
“a”的作用域是函数的局部范围。您应该返回“a”并将其分配给“A”,例如
A = foo(A);
关于javascript - 数组作为参数传递,但函数内重新分配失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24503384/