使用预定义数组初始化对象数组时,我面临很多问题。我无法将该数组复制到我的新对象数组。如果有人知道,那就告诉我。
admins
基本上是一个数组,其中包含诸如["hello","hii","sup",....]
var admins = ["hello","hii","sup"];
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i].name = admins[i];
}
console.log(obj);
“ TypeError:无法设置未定义的属性'名称'”
答案 0 :(得分:4)
使用map:
async function main() {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 800 });
await page.goto(endpoint, { waitUntil: "networkidle2", timeout: 0 });
await page.waitFor(3000);
await page.type("#username", login);
await page.type("#password", pass);
// click and wait for navigation
await page.click("#login"),
await page.waitForNavigation({ waitUntil: "networkidle2" });
await page.waitFor(2000);
const client = await page.target().createCDPSession();
await client.send("Page.setDownloadBehavior", {
behavior: "allow",
downloadPath: path.resolve(__dirname, "reports/asd")
});
await page.waitForXPath('//*[@id="ctl00_ctl00_masterMain_cphMain_repViewable_ctl01_thisItemLink"]');
const [setting] = await page.$x('//*[@id="ctl00_ctl00_masterMain_cphMain_repViewable_ctl01_thisItemLink"]');
if (setting) setting.click();
await page.waitFor(3000);
let pages = await browser.pages();
await page.waitFor(2000);
await pages[2].waitForXPath('/html/body/table/tbody/tr[17]/td[6]/a');
const [newVID] = await pages[2].$x('/html/body/table/tbody/tr[17]/td[6]/a');
if (newVID) newVID.click();
await pages[2].waitFor(3000)
await pages[2].close()
await pages[2].waitFor(5000)
await pages[2].waitForXPath('//*[@id="freeze"]/table/tbody/tr[2]/td/table/tbody/tr[3]/td/a');
const [neww] = await pages[2].$x('//*[@id="freeze"]/table/tbody/tr[2]/td/table/tbody/tr[3]/td/a');
if (neww) neww.click();
await pages[2].waitFor(4000)
await pages[2].waitFor(4000)
await pages[2].waitForXPath('/html/body/div/table/tbody/tr[3]/td/a');
const [fin] = await pages[2].$x('/html/body/div/table/tbody/tr[3]/td/a');
if (fin) fin.click();
}
main()
答案 1 :(得分:1)
恕我直言:使用传播算子:
const admins = ["John", "Doe", "Duck"];
const obj = [...admins].map(
(admin) => ({ name: admin })
);
console.log(obj);
答案 2 :(得分:-1)
尝试一下
var obj = [];
for (var i = 0; i < admins.length; i++) {
let temp = {};
temp["name"] = admins[i];
obj.push(temp);
}
console.log(obj);
答案 3 :(得分:-2)
您需要将obj [i]定义为空对象(obj [i] = {})。
您正在尝试访问未定义的名称属性(代码中未定义obj [i])。
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i] = {
name: admins[i]
}
}
console.log(obj);