所以,我有这段代码,它确实可行:
(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
isGood(key) === true ?...
没有被分配给score
变量。而这个语句:score = isGood(key) ? ...
则将值分配给了score
变量。 - zer00nelet change = parseInt(hash[key], 10); score += isGood(key) ? change : -change;
might be a more readable and less repetitive way to write this. Alternativelyreturn Object.entries(hash).reduce((score, [k, v]) => score + isGood(k) ? parseInt(v, 10) : -parseInt(v, 10))
- Stuart