我的第一个reduce返回以下形式的表达式:
a + (condition)? b : c
,第二个reduce会返回等价(???)表达式:(condition)? a+b : a+c
为什么它们的行为有所不同?
function addressLengthWrong(address) {
let keys = ['street', 'city', 'state', 'zip']
return keys.reduce((acc, key) => acc + (address[key]) ? address[key].length : 0, 0)
}
let address = {
street: 'My Street',
city: '',
state: '',
zip: ''
}
console.log(`wrong address len ${addressLengthWrong(address)}`)
address.zip = '01234'
console.log(`wrong address len ${addressLengthWrong(address)}`)
运行替代方案...
function addressLengthCorrect(address) {
let keys = ['street', 'city', 'state', 'zip']
return keys.reduce((acc, key) => (address[key]) ? acc + address[key].length : acc, 0)
}
address = {
street: 'My Street',
city: '',
state: '',
zip: ''
}
console.log(`correct address len ${addressLengthCorrect(address)}`)
address.zip = '01234'
console.log(`correct address len ${addressLengthCorrect(address)}`)
我对即将学习新东西感到很兴奋。这是怎么回事?
答案 0 :(得分:2)
您的括号顺序错误。 试试这个:
function addressLengthWrong(address) {
let keys = ['street', 'city', 'state', 'zip']
return keys.reduce((acc, key) => acc + (address[key] ? address[key].length : 0), 0)
}
您应该用括号将整个三元表达式括起来,否则将包含acc
。
还要引用安德里亚斯的答案:
... + ... precedence: 13, ... ? ... : ... precedence: 4; the higher value 'wins'
答案 1 :(得分:0)
我认为这是因为三元运算在开始时是不正确的,并且没有获得初始值。代替加号(+),在累加器上使用+ =。
let a = 1, b = 2
let c = 0
c + a === 1 ? a : b // fails, c = 0
c += a === 1 ? a : b // success, c = 1