【问题标题】:Javascript Array Push Inside While Pop LoopJavascript数组在弹出循环中推入
【发布时间】:2014-04-11 09:35:21
【问题描述】:

我已经创建了这个jsfiddle,但我无法解释为什么以下不会产生一个包含 5 个对象的数组,这些对象都具有不同的 id 属性:

var arr = ["1", "2", "3", "4", "5"];
var clone = {"id": "0", "name":"Matthew"};
var arrObj = [];

var idArr = [];

while((a=arr.pop()) != null){ 
    clone.id = a;
    console.log(clone);
    arrObj.push(clone);
}

console.log(arrObj);

我最终在控制台中得到以下内容:

Object {id: "5", name: "Matthew"} (index):28
Object {id: "4", name: "Matthew"} (index):28
Object {id: "3", name: "Matthew"} (index):28
Object {id: "2", name: "Matthew"} (index):28
Object {id: "1", name: "Matthew"} (index):28

[Object, Object, Object, Object, Object]

当我打开 5 个克隆对象中的每一个时,它们的“id”值都为“1”

这是为什么?

【问题讨论】:

  • 对象是通过引用传递的,你一遍又一遍地引用同一个对象。你需要克隆它。 stackoverflow.com/questions/122102/…
  • Add values to an array的可能重复
  • 你引用的好帖子!我永远不会找到我的答案,因为那篇文章的标题和标签如此模糊。此外,这个问题解决了在循环外引用对象并以上述方式为它们分配值的注意事项。为类似的问题带来不同的视角,但不完全是重复的。

标签: javascript arrays object while-loop


【解决方案1】:

JS 中的对象是通过引用分配的。你需要复制它,比如jQuery.extend

var arr = ["1", "2", "3", "4", "5"];
var clone = {"id": "0", "name":"Matthew"};
var arrObj = [];

var idArr = [];

while((a=arr.pop()) != null){ 
    clone = $.extend({}, clone);
    clone.id = a;
    console.log(clone);
    arrObj.push(clone);
}

console.log(arrObj);

【讨论】:

  • @elclanrs 你可以重新实现$.extend,如果它让你感到温暖和模糊。
  • 速度非常快,谢谢!我也想看到一个非 jquery 的答案,但你绝对值得勾选。我将不得不阅读更多关于 JS 中的对象引用。
  • @sabof 你将如何重新实现?
  • @ganicus 一个实现应该不难找到。只需谷歌搜索“克隆对象 javascript”。
【解决方案2】:

clone 是一个对象。在 javascript 中,对象是通过引用传递的,因此您不会在每个索引中传递不同的对象。

这是可行的方法

while((a=arr.pop()) != null){
    var clone = {"id": a, "name":"Matthew"};
    clone.id = a;
    arrObj.push(clone);
}

console.log(arrObj); 

结果:

Array [
    Object {id: "5", name: "Matthew"}
    Object {id: "4", name: "Matthew"}
    Object {id: "3", name: "Matthew"}
    Object {id: "2", name: "Matthew"}
    Object {id: "1", name: "Matthew"}
]

【讨论】:

    【解决方案3】:

    如果您的克隆不包含任何功能,您可以这样做

    while((a=arr.pop()) != null){
        clone = JSON.parse(JSON.stringify(clone));
        clone.id = a;
        console.log(clone);
        arrObj.push(clone);
    }
    

    【讨论】:

    • JSON 是 JavaScript 的子集。虽然这在本示例中有效,但许多 JavaScript 值将默认为 null
    猜你喜欢
    • 2013-10-18
    • 2012-02-18
    • 2012-07-11
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多