简体   繁体   English

使用 JavaScript 计算数字的总和

[英]Sum of a number's digits with JavaScript

I have:我有:

var nums = [333, 444, 555]; 

I want to treat each digit in a number as a separate number and add them together.我想将数字中的每个数字视为一个单独的数字并将它们加在一起。 In this case sums should be:在这种情况下,总和应该是:

9 = 3 + 3 + 3
12 = 4 + 4 + 4
15 = 5 + 5 + 5 

How to achieve this using JavaScript?如何使用 JavaScript 实现这一点?

you can use a simple modulo operation and dividing您可以使用简单的模运算和除法

var a = [111, 222, 333];

a.forEach(function(entry) {
    var sum = 0;
    while(entry > 0) 
    {
        sum += entry%10;
        entry = Math.floor(entry/10);
    }
    alert(sum)
});

Here's a different approach that converts the numbers to strings and converts those into an array of characters, then the characters back into numbers, then uses reduce to add the digits together.这是一种不同的方法,将数字转换为字符串,然后将它们转换为字符数组,然后将字符重新转换为数字,然后使用reduce将数字相加。

var nums = [333, 444, 555];
var digitSums = nums.map(function(a) {
  return Array.prototype.slice.call(a.toString()).map(Number).reduce(function(b, c) {
    return b + c;
  });
});
digitSums; // [9, 12, 15]

If your array consists of bigger numbers (that would overflow or turn to Infinity ), you can use strings in your array and optionally remove the .toString() .如果您的数组包含更大的数字(会溢出或变为Infinity ),您可以在数组中使用字符串,并可选择删除.toString()

var nums = [333, 444, 555]; 

nums.map(number => [...String(number)].reduce((acc, num) => +num+acc , 0));

//output [9, 12, 15] //输出 [9, 12, 15]

Unary plus operator (+num) is converting string into integer.一元加号运算符 (+num) 将字符串转换为整数。

If you want to generate an array consisting of the sum of each digit, you can combine the .map() / .reduce() methods.如果要生成由每个数字之和组成的数组,可以结合使用.map() / .reduce()方法。 The .map() method will create a new array based on the returned value (which is generated on each iteration of the initial array). .map()方法将根据返回值(在初始数组的每次迭代时生成.map()创建一个新数组。

On each iteration, convert the number to a string ( num.toString() ), and then use the .split() method to generate an array of numbers.在每次迭代中,将数字转换为字符串 ( num.toString() ),然后使用.split()方法生成数字数组。 In other words, 333 would return [3, 3, 3] .换句话说, 333将返回[3, 3, 3] Then use the .reduce() method to add the current/previous numbers in order to calculate the sum of the values.然后使用.reduce()方法将当前/以前的数字相加,以计算值的总和。

 var input = [333, 444, 555]; var sumOfDigits = input.map(function(num) { return num.toString().split('').reduce(function(prev, current) { return parseInt(prev, 10) + parseInt(current, 10); }, 0); }); //Display results: document.querySelector('pre').textContent = 'Input: ' + JSON.stringify(input, null, 4) + '\\n\\nOutput: ' + JSON.stringify(sumOfDigits, null, 4);
 <pre></pre>

Now in our days, with the advantages of ES6 , you can simply spread each value of your array inside map , and the with reduce make the operation:现在,利用ES6的优势,您可以简单地将数组的每个值分布map ,并且 with reduce进行操作:

 var numbers = [333, 444, 555]; const addDigits = nums => nums.map( num => [...num.toString()].reduce((acc, act) => acc + parseInt(act), 0) ); console.log(addDigits(numbers));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM