[英]Have Error : SyntaxError: Unexpected token, expected “,” - I am trying to return an array where the keys name: and timestamp: are present
Have Error: SyntaxError: Unexpected token, expected "," - I am trying to return an array where the keys name: and timestamp: are present.有错误:SyntaxError: Unexpected token, expected "," - 我试图返回一个数组,其中键名:和时间戳:存在。 by pushing into new array where keys are valid i used, but this gives me back and array where elements are undefined.
通过推入我使用的键有效的新数组,但这给了我返回元素未定义的数组。 trying to make new array where these dont exist in new array
尝试制作新数组中不存在的新数组
const newEvents = events.map(event => (event.name && event.timestamp) && {
timestamp: event.timestamp,
name: event.name,
});
//Trying to push into array here when the the keys name: and timestamp: are present. //当键名:和时间戳:存在时,尝试在此处推入数组。 //But, getting a Unexpected error ","
//但是,得到一个意外错误“,”
const newerEvents =[];
for (const ele of events){
(ele.name && ele.timestamp) && { newerEvents.push({name: ele.name, timestamp:
ele.timestamp}) }
}
Any help is greatly appreciated, thanks非常感谢任何帮助,谢谢
The curly braces here are being treated as an object literal instead of a "short-circuit" code block:这里的花括号被视为object 文字而不是“短路”代码块:
(ele.name && ele.timestamp) && { /* this is an object, not a code block */ }
You can fix this by either:您可以通过以下任一方式解决此问题:
Omitting the curly braces {}
:省略花括号
{}
:
(ele.name && ele.timestamp) && newerEvents.push({name: ele.name, timestamp: ele.timestamp})
an if
(for when you need multiple statements): if
(当您需要多个语句时):
//populate const events = [{timestamp: new Date().getTime(), name: "hi"}]; const newEvents = events.map(event => (event.name && event.timestamp) && { timestamp: event.timestamp, name: event.name, }); const newerEvents = []; for (const ele of events) { if (ele.name && ele.timestamp) { newerEvents.push({name: ele.name, timestamp: ele.timestamp}); } } //output console.log(newerEvents);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.