给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
给定一个数组[1,2,3,4],如何求其元素的和?(在这种情况下,总数为10。)
我认为每个美元可能有用,但我不确定如何实现它。
当前回答
建议(使用默认值减少)
Array.prototype.reduce可用于遍历数组,将当前元素值与先前元素值之和相加。
控制台日志([1,2,3,4].减少((a,b)=>a+b,0))控制台日志([].减少((a,b)=>a+b,0))
无默认值
你得到一个TypeError控制台日志([].减少((a,b)=>a+b))
ES6箭头功能之前
控制台日志([1,2,3].reduce(函数(acc,val){return acc+val;},0))控制台日志([].reduce(函数(acc,val){return acc+val;},0))
非数字输入
如果非数字是可能的输入,您可能想处理它?控制台日志([“hi”,1,2,“frog”].减少((a,b)=>a+b))让numOr0=n=>isNaN(n)?0:n控制台日志([“hi”,1,2,“frog”].减少((a,b)=>numOr0(a)+numOr0)
非推荐危险评估用途
我们可以使用eval来执行JavaScript代码的字符串表示。使用Array.prototype.join函数将数组转换为字符串,我们将[1,2,3]更改为“1+2+3”,其值为6。
控制台日志(eval([1,2],3],join('+')))//如果建立阵列,这种方式很危险//因为它可能被利用,例如:eval([1,“2;alert('恶意代码!')”].join('+'))
当然,显示警报并不是可能发生的最糟糕的事情。我之所以将此作为奥特蒙德问题的答案,是因为我认为这一问题没有得到澄清。
其他回答
Vanilla JavaScript是您所需要的一切:
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(function(e){sum += e}); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; a.forEach(e => sum += e); sum
10
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e in a) sum += e; sum
"00123foobar"
> a = [1,2,3,4]; a.foo = 5; a['bar'] = 6; sum = 0; for(e of a) sum += e; sum
10
有人在找像我这样的功能性的oneliner吗?
假设:
const arr = [1, 2, 3, 4];
这是现代JS的一条直线:
sum = arr.reduce((a, b) => a + b, 0);
(如果您碰巧需要支持没有箭头功能的旧IE:)
sum = arr.reduce(function (a, b) {return a + b;}, 0);
注意,这里的初始值是0,因此如果需要,可以将其用作偏移量。还要注意,需要这个初始值,否则使用空数组调用函数将出错。
标准JavaScript解决方案:
var addition = [];
addition.push(2);
addition.push(3);
var total = 0;
for (var i = 0; i < addition.length; i++)
{
total += addition[i];
}
alert(total); // Just to output an example
/* console.log(total); // Just to output an example with Firebug */
这对我有用(结果应该是5)。我希望这种解决方案没有隐藏的缺点。
没有人提到函数式编程,但在这种情况下使用Ramda是非常干净的方法:
//Assuming you use nodejs, but can also be used in browser
const R = require('ramda');
let nums = [2, 4, 6, 8, 10];
console.log(R.sum(nums));
<!DOCTYPE html>
<html>
<body>
<p>Click the button to join two arrays.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
console.log((hege.length > stale.length))
var children = (hege.length > stale.length)? abc1() :abc2(); document.getElementById("demo").innerHTML = children;
}
function abc1(){
console.log(hege,"Abc1")
var abcd=hege.map(function (num, idx) {
console.log(hege.length , idx)
return stale.length>idx?num + stale[idx]:num;
})
return abcd;
}
function abc2(){
console.log(hege,"Abc2",stale)
var abcd=stale.map(function (num, idx) {
console.log(hege.length , idx)
return hege.length>idx?num + hege[idx]:num;
})
return abcd;
}
</script>
</body>
</html>