写一个求和的函数sum,达到下面的效果
// Should equal 15 sum(1, 2, 3, 4, 5); //Should equal 0 sum(5, ‘abc‘, -5); //Should equal 4 sum(1, true, ‘a‘, ‘D‘, 1, ‘F‘, 1, ‘w‘);
下面附上多种方法:
function sum(){ var add = 0; for(var i = 0; i < arguments.length; i++){ if(!isNaN(Number(arguments[i]))){ add += Number(arguments[i]); } } alert(add); } sum(1,2,3,4,5); sum(5,‘asd‘,-5); sum(1, true, ‘a‘, ‘D‘, 1, ‘F‘, 1, ‘w‘);
普通的方法
var sum = function() { return [].slice.call(arguments).map(function(x) { return isNaN(Number(x)) ? 0 : Number(x); }).reduce(function(a, b) { return a + b; }); }
map&reduce方法
var sum = function(){ return [].reduce.call(arguments, function(a,b){return (parseFloat(+a)||0)+(parseFloat(+b)||0)}) }
再改
时间: 2024-09-11 17:06:07