在对JS用法进行一些基本测试期间,我一直在研究对象的生成/数组的添加。到目前为止,我已经使用两种不同的方法来解决此问题:
尽管在运行时没有错误,但全局对象属性上的value字段始终输出2
(此处的值假定随循环而增加),而函数方法似乎没有问题。您知道为什么会这样吗?
我生成的最终输出是"[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"
(来自console.log(JSON.stringify(testArray));
)。
我期望输出"[{"name":"Hello","value":0},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"
相关功能和对象的代码可以在下面找到。
定义全局变量:
var globalVariable =
{
name: undefined,
value: undefined
}
工厂功能:
function globalVariableGen(name, valueInput)
{
return output =
{
name: name,
value: valueInput + 1
}
}
数组生成函数:
function test2()
{
var i, testArray = [];
for (i = 0; i < 3; i++)
{
alert(i.toString());
globalVariable.name = "Hello";
globalVariable.value = i;
testArray.push(globalVariable);
testArray.push(globalVariableGen("Hello World", i));
}
console.log(JSON.stringify(testArray));
}
亲切的问候, 阴影
答案 0 :(得分:4)
这是因为javascript是传递引用,并且您指的是多次添加到数组中的同一globalVariable
。然后,该数组包含多个指向globalVariable的指针,它们完全相同。
如果将console.log(JSON.stringify(testArray)
添加到循环中,您将看到此行为。
> "[{"name":"Hello","value":0},{"name":"Hello World","value":1}]"
> "[{"name":"Hello","value":1},{"name":"Hello World","value":1},{"name":"Hello","value":1},{"name":"Hello World","value":2}]"
> "[{"name":"Hello","value":2},{"name":"Hello World","value":1},{"name":"Hello","value":2},{"name":"Hello World","value":2},{"name":"Hello","value":2},{"name":"Hello World","value":3}]"