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


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01