简体   繁体   English

JS-Object.keys()中的三元语句

[英]JS - ternary statement inside Object.keys()

When I put a ternary statement or an if statement inside the Object.keys() like bellow: 当我像下面这样在Object.keys()中放入ternary statementif statement

 Object.keys(date).forEach((index) => {
        dates[date[index].id] !== undefined ?
          dates[date[index].id] =
          [...dates[dates[date[index].id], dates[date[index].name]
          : null;
      });

I get this error from the Linter: 我从Linter收到此错误:

Expected an assignment or function call and instead saw an expression. (no-unused-expressions)

When I use a regular if statement, I get this error, 当我使用常规的if语句时,出现此错误,

Parsing error: Unexpected token (Fatal)

Why? 为什么?

You've duplicated dates in and got some missing brackets in the assignment: 您输入了重复的dates ,并在作业中遗漏了一些括号:

dates[date[index].id] = [...dates[dates[date[index].id], dates[date[index].name]

Which should be: 应该是:

dates[date[index].id] = [..dates[date[index].id], dates[date[index].name]]

Demo: 演示:

Object.keys(date).forEach((index) => dates[date[index].id] !== undefined ?
        dates[date[index].id] = [...dates[date[index].id], dates[date[index].name]] : null);

You could use a regular if condition, without a ternary expression, which the linter does not like. 您可以使用常规条件条件,而没有三叉戟不喜欢的三元表达式。

Object.keys(date).forEach((index) => {
    if (dates[date[index].id] !== undefined) {
        dates[date[index].id] = [
            ...dates[dates[date[index].id]],
            dates[date[index].name]
        ];
    }
});

Basically the tenary is used with an assignment outside of the operator, like 基本上,tenary与操作员外部的作业一起使用,例如

x = a > 4 ? 7: 8;

whereas your assignment takes place inside of the operator. 而您的分配是在操作员内部进行的。

You just have a few syntax errors in there, probably stemming from the overcomplicated nesting of property accesses. 您那里只有一些语法错误,可能是由于属性访问的嵌套过于复杂。 Keep it simple: 把事情简单化:

for (const index in date) {
    const id = date[index].id;
    if (dates[id] !== undefined) {
        dates[id].push(date[index].name);
        // or if you insist:
        // dates[id] = [...dates[id], date[index].name];
    }
}

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

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