gpt4 book ai didi

javascript - 为什么在创建对象数组时出现错误?

转载 作者:行者123 更新时间:2023-11-30 13:52:07 25 4
gpt4 key购买 nike

我的目标是创建一个 JavaScript 对象数组,并希望输出采用如下格式:

journal = [
{
events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"
],
squirrel: false
},
{
events: ["weekend", "cycling", "break", "peanuts",
"soda"
],
squirrel: true
}

];

目标是使用给定的参数(事件和松鼠)从以下函数构建

let journal = [];

function addEntry(events, squirrel) {
...........
...........
}

我写了下面的代码,输出给我一个错误:“false is not a function”。如何修复该错误并获得预期的输出?谢谢

let journal = [];

function addEntry(events, squirrel) {
journal.push(
({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]
}, false)
({
events: ["weekend", "cycling", "break", "peanuts", "soda"]
}, true)
)
}
addEntry(console.log(journal));

最佳答案

当您使用push 推送多个值时,您需要用, 将它们分开。这里你有这种格式的 (obj,false)(),因为逗号运算符返回最后一个操作数,所以你实际上结束了 false()

let journal = [];

function addEntry(events, squirrel) {
journal.push(
({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]
}, false),
({
events: ["weekend", "cycling", "break", "peanuts", "soda"]
}, true)
)
}
addEntry(journal);
console.log(journal)

在这里,如果您打算只推送对象,则不需要包装 () 并且如果您需要对象中的多个属性,则可以像这样添加内部对象

 {
key: value,
key: value
}

let journal = [];

function addEntry(events, squirrel) {
journal.push({...events,squirrel})
}
addEntry({
events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"]},true);
addEntry({
events: ["weekend", "cycling", "break", "peanuts", "soda"]},false)
console.log(journal)

关于javascript - 为什么在创建对象数组时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58036854/

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