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

时间:2019-09-21 02:41:16

标签: javascript javascript-objects

我的目标是创建一个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不是函数”。如何解决该错误并获得预期的输出? 谢谢

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));

2 个答案:

答案 0 :(得分:2)

使用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)

答案 1 :(得分:0)

您输入的语法不正确

  1. 您将console.log方法的结果传递给addEntry方法,这没有意义

  2. 您在addEntry方法()中使用了({ events: [...] }, false),这是一个语法错误,您需要推送一个对象(由{}包装,如下所示:{{1 }}

这是示例代码:

({ events: [...], squirrel : false })