JavaScript三元条件语句,将其赋值给变量并递增

4

所以,我有这段代码,它确实可行:

(hash将是类似于 {"bob" => "12", "Roger" => "15" 等的对象},isGood(key) 是调用函数 isGood 来判断球员好坏的函数。)
let score = 0;
Object.keys(hash).forEach((key) => {
  isGood(key) === true ? score += parseInt(hash[key], 10) : score -= parseInt(hash[key], 10);
});
return score;

我得到了这个错误信息:

Expected an assignment or function call and instead saw an expression

我成功地使其运行,而没有出现此错误消息,就像这样:

let score = 0;
Object.keys(hash).forEach((key) => {
  score = isGood(key) ? score + parseInt(hash[key], 10) : score - parseInt(hash[key], 10);
});
return score;

但是,为什么第一种方法不是正确的方式,即使它能够工作?很抱歉我在JavaScript约定方面有些问题。 先行致谢! Olivier


1
三元运算需要一个变量来存储结果。这个语句: isGood(key) === true ?... 没有被分配给 score 变量。而这个语句: score = isGood(key) ? ... 则将值分配给了 score 变量。 - zer00ne
1
let change = parseInt(hash[key], 10); score += isGood(key) ? change : -change; might be a more readable and less repetitive way to write this. Alternatively return Object.entries(hash).reduce((score, [k, v]) => score + isGood(k) ? parseInt(v, 10) : -parseInt(v, 10)) - Stuart
谢谢,我现在明白了!同时也感谢 Stuart 介绍 reduce 给我,我会更仔细地研究它。 - Olivier Girardot
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接