简体   繁体   English

如何解决推入单个 arrays 的 javascript 对象而不是将所有对象推入单个数组?

[英]How to resolve javascript objects pushed in to individual arrays instead of all of them being pushed into a single array?

I have a javascript code as below:我有一个 javascript 代码如下:

function ready() {

    var items = document.querySelectorAll('.item')

    for (var i = 0; i < items.length; i++) {
        var current = items[i];

        var name = current.getElementsByClassName('item-title')[0].innerText;
        var price = parseInt(current.getElementsByClassName('item-price')[0].innerText);

        var data = [];

        var products = {};
        products.title = name;
        products.cost = price;
        data.push(products);

        //console.log(products)

        console.log(data)

    }
    
}

On running the code, I get the result as:在运行代码时,我得到的结果如下:

[{title: "Jack Daniels 1L", cost: 60}]
[{title: "Southern Comfort 2L", cost: 130}] 
[{title: "Golden Label 1L", cost: 120}]
[{title: "Grey Goose 1L", cost: 31}]
[{title: "Remy Martins 750ml", cost: 45}]
[{title: "Hennessy 1L", cost: 68}]
[{title: "Johnnie Walker 1L", cost: 50] 
[{title: "Double Black 750ml", cost: 55}]

Yet I'm looking for a result that looks like this:然而我正在寻找一个看起来像这样的结果:

[ {title: "Jack Daniels 1L", cost: 60}, 
   {title: "Southern Comfort 2L", cost: 130}, 
   {title: "Golden Label 1L", cost: 120}, 
   {title: "Grey Goose 1L", cost: 31}, 
   {title: "Remy Martins 750ml", cost: 45}, 
   {title: "Hennessy 1L", cost: 68}, 
   {title: "Johnnie Walker 1L", cost: 50}, 
   {title: "Double Black 750ml", cost: 55} ]

I have looked at solutions to questions asked that are related to mine but I keep getting the same result at best.我已经查看了与我相关的问题的解决方案,但我最多只能得到相同的结果。 What do I need to include or remove?我需要包含或删除什么? Or what is the best way to go about it?或者go 最好的方法是什么? Thank you.谢谢你。

So this is due to data being defined in each iteration.所以这是由于在每次迭代中都定义了data Move it out and it will work把它移出来,它会工作

function ready() {

    var items = document.querySelectorAll('.item')

    var data = [];

    for (var i = 0; i < items.length; i++) {
        var current = items[i];

        var name = current.getElementsByClassName('item-title')[0].innerText;
        var price = parseInt(current.getElementsByClassName('item-price')[0].innerText);

        var products = {};
        products.title = name;
        products.cost = price;
        data.push(products);

        //console.log(products)

    }

   console.log(data)
    
}

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

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