Javascript中奇怪的数组赋值

时间:2015-03-17 21:54:03

标签: javascript arrays

我有以下内容:

alert("before: " + JSON.stringify(scenario_data)); // Outputs: {"1":{"amount":{"value":"","inputflag":false},"numberout":{"value":"","inputflag":false},"discount":{"value":"","inputflag":false}},"2":{"amount":{"value":"","inputflag":false},"numberout":{"value":"","inputflag":false},"discount":{"value":"","inputflag":false}}}

scenario_data[1]['amount']['value'] = 1234;

alert("After: " + JSON.stringify(scenario_data)); // Outputs: {"1":{"amount":{"value":1234,"inputflag":true},"numberout":{"value":"","inputflag":false},"discount":{"value":"","inputflag":false}},"2":{"amount":{"value":1234,"inputflag":true},"numberout":{"value":"","inputflag":false},"discount":{"value":"","inputflag":false}}}

为什么scenario_data[1]['amount']['value']scenario_data[2]['amount']['value']都设置为1234

1 个答案:

答案 0 :(得分:4)

因为scenario_data[0]scenario_data[1]指向同一个对象。因此,当您转换为json时,两个元素具有相同的表示形式。您可以通过检查scenario_data[0] == scenario_data[1]的值来验证。