[英]How to resolve javascript objects pushed in to individual arrays instead of all of them being pushed into a single array?
我有一個 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)
}
}
在運行代碼時,我得到的結果如下:
[{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}]
然而我正在尋找一個看起來像這樣的結果:
[ {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} ]
我已經查看了與我相關的問題的解決方案,但我最多只能得到相同的結果。 我需要包含或刪除什么? 或者go 最好的方法是什么? 謝謝你。
所以這是由於在每次迭代中都定義了data
。 把它移出來,它會工作
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.