Methods to implement summation in JavaScript: 1. Sum through the "function sumArr(arr){...}" method; 2. Sum through forEach traversal; 3. Through "eval(arr.join (" "))" method to sum.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
Sum method in javascript
JS array sum method
Array summation, generally our idea is to traverse the array items , and then add up.
That’s it:
function sumArr(arr){ var sum = 0; for(var i = 0;i<=arr.length;i++){ sum += arr[i];//前提是arr中各项是数字,而不是数字字符串 //如果是数字字符串:sum += Number(arr[i]); } return sum; }
Or forEach traversal:
function sumArr(arr){ var sum = 0; arr.forEach(function(val,index,arr){ sum += val; }) return sum; }
There is also a more black-tech writing method:
function sumArr(arr){ return eval(arr.join("+")) }//直接把他变成各个数的加法运算字符串
Of course there is this A widely praised way of writing functional programming:
function sumArr(arr){ return arr.reduce(function(prev,cur){ return prev + cur; },0); } //reduce方法有两个参数,一个是callbackfunction(回调函数), //二是设置prev的初始类型和初始值
There is a written test question: (This summarizes the article)
Given any non-negative integer, repeatedly accumulate the digits until the result is a single digit. For example, given a non-negative integer 912, the first accumulation is 9 1 2 = 12, the second accumulation is 1 2 = 3, 3 is a single digit, and 3 is returned when the loop terminates. Please program it.
function add(num){ if(isNaN(num)) return; if(num<10) return num const res=num.toString().split('').reduce((sum,value)=>{ return sum+Number(value) },0) return add(res); } add(345); 3
Recommended study: "javascript Advanced Tutorial"
The above is the detailed content of Summing method in javascript. For more information, please follow other related articles on the PHP Chinese website!