gpt4 book ai didi

arrays - Array .push 在每个循环内返回用相同对象填充的数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:18 24 4
gpt4 key购买 nike

我正在尝试使用 CheeriosJS 来抓取页面以获取一些信息。问题是我需要每个循环来覆盖变量并将该变量推送到空数组。虽然我正确地进行了网页抓取(每个循环我得到一个不同的对象),但当我在循环完成后打印数组时,我得到的数组具有多次重复的同一对象。我在这里缺少什么?

const rp = require('request-promise');
const $ = require('cheerio');

let marketSpain = {
country: 'Spain',
name: 'IBEX 35',
companies: []
}

let companySpain = {
name: null,
last: null,
high: null,
low: null,
change: null,
changePerCent: null,
volume: null,
time: null,
purchase: false,
sale: false
}

rp({
uri: 'url',
headers: {
'User-Agent': 'Request-Promise'
}
}).then(html => {
$("table[class='genTbl closedTbl crossRatesTbl elpTbl elp30'] > tbody > tr", html).each((i, elem) => {
companySpain.name = $("td[class='bold left noWrap elp plusIconTd'] > a", html).eq(i).html();
companySpain.last = $("td", elem).eq(2).text();
companySpain.high = $("td", elem).eq(3).text();
companySpain.low = $("td", elem).eq(4).text();
companySpain.change = $("td", elem).eq(5).text();
companySpain.changePerCent = $("td", elem).eq(6).text();
companySpain.volume = $("td", elem).eq(7).text();
companySpain.time = $("td", elem).eq(8).text();

marketSpain.companies.push(companySpain);
});
console.log(marketSpain)
markets.push(marketSpain);


}).catch(err => {
console.log(err);
})

最佳答案

您正在修改同一对象并将其附加到列表末尾。你想做的是这样的:

const rp = require('request-promise');
const $ = require('cheerio');

let marketSpain = {
country: 'Spain',
name: 'IBEX 35',
companies: []
}

rp({
uri: 'url',
headers: {
'User-Agent': 'Request-Promise'
}
}).then(html => {
$("table[class='genTbl closedTbl crossRatesTbl elpTbl elp30'] > tbody > tr", html).each((i, elem) => {
marketSpain.companies.push({
name: $("td[class='bold left noWrap elp plusIconTd'] > a", html).eq(i).html(),
last: $("td", elem).eq(2).text(),
high: $("td", elem).eq(3).text(),
low: $("td", elem).eq(4).text(),
change: $("td", elem).eq(5).text(),
changePerCent: $("td", elem).eq(6).text(),
volume: $("td", elem).eq(7).text(),
time: $("td", elem).eq(8).text(),
purchase: false,
sale: false
});
});
console.log(marketSpain)
markets.push(marketSpain);


}).catch(err => {
console.log(err);
})

关于arrays - Array .push 在每个循环内返回用相同对象填充的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com