推荐(减少默认值)
Array.prototype.reduce可用于遍历数组,将当前元素值添加到先前元素值的总和中。
console.log( [1, 2, 3, 4].reduce((a, b) => a + b, 0))console.log( [].reduce((a, b) => a + b, 0))
没有默认值
您收到TypeError
console.log( [].reduce((a, b) => a + b))
在ES6的箭头功能之前
console.log( [1,2,3].reduce(function(acc, val) { return acc + val; }, 0))console.log( [].reduce(function(acc, val) { return acc + val; }, 0))非数字输入
如果非数字是可能的输入,您可能要处理呢?
console.log( ["hi", 1, 2, "frog"].reduce((a, b) => a + b))let numOr0 = n => isNaN(n) ? 0 : nconsole.log( ["hi", 1, 2, "frog"].reduce((a, b) => numOr0(a) + numOr0(b)))
不建议危险的评估使用
我们可以使用eval执行Javascript代码的字符串表示形式。使用Array.prototype.join函数将数组转换为字符串,我们将[1,2,3]更改为“1 + 2 + 3”,其结果为6。
console.log( eval([1,2,3].join('+')))//This way is dangerous if the array is built// from user input as it may be exploited eg:eval([1,"2;alert('Malicious pre!')"].join('+'))当然,显示警报并不是可能发生的最糟糕的事情。我将其包括在内的唯一原因是作为对Ortund问题的回答,因为我认为这没有得到澄清。



