Sum all the digits of a number Javascript(总结一个数字的所有数字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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:总结一个数字的所有数字Javascript


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06