简体   繁体   English

Javascript array.push替换先前添加的元素

[英]Javascript array.push replacing previously added elements

I'm filling in an array with objects. 我用对象填充数组。 Each time the for loop iterates, it's updating the previous items of the array. 每次for循环迭代时,它都会更新数组的先前项目。

I've tried with various types of loops like for-each, for and for of. 我已经尝试过各种类型的循环,例如for-each,for和for of。

var arrResult = new Array;

for (let element of accessoriesToDisplay) {
    var obj = {};
    var obj = await AdaptiveCardImporter.accessoryCard(element.Name,
     element.Price, element.ProductDescription, element.URL, element.ImgURL);
    arrResult.push(obj);
}

This array should have 3 different objects at the end and not the array filled in with just the last one. 该数组的末尾应该有3个不同的对象,而不是仅用最后一个填充的数组。 This code was working before I moved the accessoryCard method outside the main js file. 在我将annexantCard方法移至主要js文件之外之前,此代码已起作用。

Watcher: 观察者:

循环1

Loop 2

循环3

You code concept is fine. 您编码的概念很好。 You code should execute normally, but you problem lies with your await - something there isn't right. 您的代码应该可以正常执行,但是问题出在等待中-某些事情不正确。 For example this recreation of your code works: 例如,重新编写代码的工作原理是:

 const getObj = e => new Promise(resolve => setTimeout(() => resolve({val:e}), 300)) async function main() { var arrResult = [] var accessoriesToDisplay = [1, 2, 3] for (let element of accessoriesToDisplay) { var obj = await getObj(element) console.log(obj) arrResult.push(obj); } console.log(arrResult) } main() 

But your code does not. 但是您的代码却没有。 Try console.log(JSON.stringify(obj)) on each loop iteration to check if the object returned is actually the object you are looking for - chrome likes to help out by automatically updating the value. 在每次循环迭代中尝试使用console.log(JSON.stringify(obj))来检查返回的对象是否实际上是您要查找的对象console.log(JSON.stringify(obj))喜欢通过自动更新值来提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM