【问题标题】:Push in typescript is appending the last modified object in a loop推入打字稿正在循环中附加最后修改的对象
【发布时间】:2021-12-05 09:40:10
【问题描述】:

我试图从修改后的对象中创建一个数组,但Array<any>.push() 方法总是在循环结束时附加被修改的对象。这是我正在尝试使用的示例代码:

let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}');
let myObject:any;
let idMapping: any[] = [];
for(let index = 0; index < 1; index++) {
    myObject = {DocID: "", index: index};
    for (let val of data.messages) {
        myObject.DocID = val.id;
        // console.log("After update: ", myObject); // this gives me the correct object
        idMapping.push(myObject);
    }
}
console.log(idMapping) // array with same identical values, infact the last modified value in for loop

这给了我一个相同对象的列表,而我期望它是一个具有不同DocID 的对象列表。

我是 typescript 和 Nodejs 的新手,因此我们将不胜感激。

【问题讨论】:

    标签: javascript node.js arrays typescript


    【解决方案1】:

    你一遍又一遍地修改和添加 same 对象到数组中!

    相反,您应该在每次迭代时创建一个新对象:

    let data: any = JSON.parse('{"messages":[{"id":"1234"},{"id":"2345"},{"id":"3456"}]}');
    let idMapping: any[] = [];
    for(let index = 0; index < 1; index++) {
       
        for (let val of data.messages) {
           let myObject = {DocID: "", index: index};
            myObject.DocID = val.id;
            // console.log("After update: ", myObject); // this gives me the correct object
            idMapping.push(myObject);
        }
    }
    console.log(idMapping)
    

    【讨论】:

    • 但是对象每次迭代都有不同的值,push()是只推送对象的引用还是对象的副本?
    • @adtyson JavaScript 从不复制对象,除非你明确告诉它这样做,所以不。您只需添加参考。
    猜你喜欢
    • 1970-01-01
    • 2020-06-10
    • 2018-09-12
    • 2018-05-11
    • 1970-01-01
    • 2017-08-28
    • 2017-10-21
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多