【发布时间】:2014-07-01 06:02:14
【问题描述】:
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? 中一样@ in assignment 什么的。
【问题讨论】:
-
变量在 JavaScript 中按值传递。它也区分大小写,所以
A!==a.
标签: javascript arrays function variable-assignment