繁体   English   中英

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

[英]Why am I getting an error when creating an array of objects?

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

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

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

 let journal = []; function addEntry(events, squirrel) {........... ........... }

我写了下面的代码,output 给了我一个错误:“false 不是函数”。 如何修复该错误并获得预期的 output? 谢谢

 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)

在这里,如果您打算只推送 object,则不需要包装() ,并且如果您在 object 中需要多个属性,则可以在 object 中添加多个属性,如下所示

 {
   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. 您将console.log方法的结果传递给addEntry方法,这是没有意义的

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

这是示例代码:

let journal = [];

function addEntry(events) {
  events.forEach(event => journal.push(event));
}

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

addEntry(events);
console.log(journal);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM