在数组中推送对象

IT技术 javascript arrays object
2021-03-09 21:47:19
 var p = {
     id: null
 };
 for (var copyArray = [], i = 0; i < 3; i++) {
     copyArray.push(p);
     copyArray[i].id = (copyArray.length) - parseInt(1, 10);
 }
 console.log(copyArray);

copyArray 中的所有 id 都获得 2 个值。结果 CopyArray({id=2},{id=2},{id=2})

对数组中的对象进行正常的push操作,插入后更新索引。

但不知何故,复制数组中的所有 id 都得到相同的 id 我在这里做错了什么

2个回答

您将同一个对象反复送到数组中,并随时更新该id对象属性。

如果您希望数组中有多个对象,则需要创建多个对象:

var copyArray = [];
while (copyArray.length < 3) {
  copyArray.push({
    id: copyArray.length
  });
}
snippet.log(JSON.stringify(copyArray));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

它奏效了,谢谢.. 有什么解释为什么我们不能那样做吗?
2021-04-18 21:47:19
@KunalVashist:第一句话是解释:你反复同一个对象
2021-04-19 21:47:19

您还可以创建一个函数来为对象创建克隆:

JSON.clone = function(json) {
    var
        temp = null,
        key = null;

    if (json === null || typeof json !== 'object') {
        return json;
    }
    temp = json.constructor(); // changed
    for (key in json) {
        if (json.hasOwnProperty(key)) {
            temp[key] = JSON.clone(json[key]);
        }
    }
    return temp;
};

然后你可以使用你的原始代码,但几乎没有变化:

var p = {
    id: null
};
for (var copyArray = [], i = 0; i < 3; i++) {
    copyArray.push(JSON.clone(p));
    copyArray[i].id = copyArray.length - 1;
}
console.log(copyArray);
为什么对这个答案投反对票?
2021-04-21 21:47:19