总结一个数字的所有数字Javascript [英] Sum all the digits of a number Javascript

查看:40
本文介绍了总结一个数字的所有数字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 的整数部分.继续.

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);

  • 使用字符串操作

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

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);

要返回值,您需要添加 value 属性.

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天全站免登陆