javascript - 数组作为参数传递,但函数内重新分配失败?

标签 javascript arrays function variable-assignment

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 的代码应该 runA = A.map(whatever),就像在 bar? 我有一些模糊的猜测,它是 javascript 如何处理 array pointersassignment 或者其他什么。

最佳答案

“a”的作用域是函数的局部范围。您应该返回“a”并将其分配给“A”,例如

A = foo(A);

关于javascript - 数组作为参数传递,但函数内重新分配失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24503384/

相关文章:

javascript - AngularJS 提供者功能

Java:如何对 3d 数组的一部分进行排序?

javascript - jQuery/JavaScript - 在函数中获取点击按钮本身

java-me - 如何在 J2ME 中将 byte[] 转换为 base64(以及返回)?

c - 在不使用结构的情况下添加多项式的数量

php - 在 XSLT 中进行文件路径操作

r - 带有 ifelse 和两个对象的自定义函数需要以动态方式从正确的列中读取 R

javascript - setInterval 有效但延迟了一个周期

javascript - jQuery - 选择标签,然后选择带有文本的子标签,然后选择同级标签

javascript - 如何在 vue.js 对象内循环数组