求和数字Javascript的所有数字 [英] Sum all the digits of a number Javascript

查看:189
本文介绍了求和数字Javascript的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手。

我想制作一个小应用程序,它将计算一个数字的所有数字的总和。

I want to make small app which will calculate the sum of all the digits of a number.

例如,如果我的数字是2568,则应用程序将计算2 + 5 + 6 + 8,其等于21.最后,它将计算21位数的总和,最终结果将为3 。

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .

请帮助我

推荐答案

基本上你有两种方法可以得到整数的所有部分的总和。

Basically you have two methods to get the sum of all parts of an integer number.


  • 使用数值运算

取数字并构建剩余的10并添加。然后将数字除法的整数部分乘以10.继续。

Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.

var value = 2568,
    sum = 0;

while (value) {
    sum += value % 10;
    value = Math.floor(value / 10);
}

console.log(sum);


  • 使用字符串操作

将数字转换为字符串,拆分字符串并得到一个包含所有数字的数组,并为每个部分执行reduce并返回总和。

Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.

var value = 2568,
    sum = value
        .toString()
        .split('')
        .map(Number)
        .reduce(function (a, b) {
            return a + b;
        }, 0);

console.log(sum);

要返回该值,您需要添加属性。

For returning the value, you need to addres the value property.

rezultat.value = sum;
//      ^^^^^^

function sumDigits() {
    var value = document.getElementById("thenumber").value,
        sum = 0;

  while (value) {
      sum += value % 10;
      value = Math.floor(value / 10);
  }
  
  var rezultat = document.getElementById("result");
  rezultat.value = sum;
}

<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>

这篇关于求和数字Javascript的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆