JavaScript 数字拆分为单个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7784620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Number Split into individual digits
提问by jonnyhitek
I am trying to solve a math problem where I take a number e.g. 45, or 111 and then split the number into separate digits e.g. 4 5 or 1 1 1. I will then save each number to a var to run a method on. Does anyone know how to split a number into individual digitals?
我正在尝试解决一个数学问题,其中我取一个数字,例如 45 或 111,然后将该数字拆分为单独的数字,例如 4 5 或 1 1 1。然后我将每个数字保存到一个 var 以运行一个方法。有谁知道如何将数字拆分为单个数字?
For example I have a loop that runs on an array :
例如,我有一个在数组上运行的循环:
for (var i = 0; i < range.length; i++) {
var n = range[i];
}
For each number, I would like to split its digits and add them together?
对于每个数字,我想拆分其数字并将它们加在一起?
回答by Brian Glaz
var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);
回答by Lapple
var number = 12354987,
output = [],
sNumber = number.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
console.log(output);
/* Outputs:
*
* [1, 2, 3, 5, 4, 9, 8, 7]
*/
UPDATE:Calculating a sum
更新:计算总和
for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);
/*
* Outputs: 39
*/
回答by Shadow Wizard is Ear For You
You can also do it in the "mathematical" way without treating the number as a string:
您也可以以“数学”方式进行操作,而无需将数字视为字符串:
var num = 278;
var digits = [];
while (num > 0) {
digits.push(num % 10);
num = parseInt(num / 10);
}
digits.reverse();
console.log(digits);
One upside I can see is that you won't have to run parseInt()
on every digit, you're dealing with the actual digits as numeric values.
我可以看到的一个好处是,您不必parseInt()
在每个数字上运行,而是将实际数字作为数值处理。
回答by Marco Gaspari
This is the shortest I've found, though it does return the digits as strings:
这是我发现的最短的,尽管它确实将数字作为字符串返回:
let num = 12345;
[...num+''] //["1", "2", "3", "4", "5"]
Or use this to get back integers:
或者使用它来取回整数:
[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]
回答by Dexygen
I will provide a variation on an answer already given so you can see a different approach that preserves the numeric type all along:
我将提供已经给出的答案的变体,以便您可以看到一种始终保留数字类型的不同方法:
var number = 12354987,
output = [];
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
console.log(output.reverse().join(',')); // 1,2,3,5,4,9,8,7
I've used a technique such as the above to good effect when converting a number to Roman numerals, which is one of my favorite ways to begin to learn a programming language I'm not familiar with. For instance here is how I devised a way to convert numbers to Roman numerals with Tcl slightly after the turn of the century: http://code.activestate.com/recipes/68379-conversion-to-roman-numerals/
在将数字转换为罗马数字时,我使用了上述技术,效果很好,这是我开始学习我不熟悉的编程语言的最喜欢的方法之一。例如,这里是我在世纪之交之后设计一种使用 Tcl 将数字转换为罗马数字的方法:http: //code.activestate.com/recipes/68379-conversion-to-roman-numerals/
The comparable lines in my Tcl script being:
我的 Tcl 脚本中的可比行是:
while {$arabic} {
set digit [expr {$arabic%10}]
set arabic [expr {$arabic/10}]
回答by Narendra Yadala
You can work on strings instead of numbers to achieve this. You can do it like this
您可以使用字符串而不是数字来实现这一点。你可以这样做
(111 + '').split('')
This will return an array of strings ['1','1','1']
on which you can iterate upon and call parseInt
method.
这将返回一个字符串数组['1','1','1']
,您可以对其进行迭代和调用parseInt
方法。
parseInt('1') === 1
If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this
如果你想要单个数字的总和,你可以像这样使用 reduce 函数(从 Javascript 1.8 实现)
(111 + '').split('').reduce(function(previousValue, currentValue){
return parseInt(previousValue,10) + parseInt(currentValue,10);
})
回答by le_m
// Split positive integer n < 1e21 into digits:
function digits(n) {
return Array.from(String(n), Number);
}
// Example:
console.log(digits(1234)); // [1, 2, 3, 4]
回答by makkBit
I used this simple way of doing it.
我使用了这种简单的方法。
To split digits
分割数字
var N = 69;
var arr = N.toString().split('').map(Number)
// outputs [6,9]
console.log( arr );
To add them together
将它们加在一起
console.log(arr.reduce( (a,b) => a+b )); // 15
回答by karaxuna
Without converting to string:
不转换为字符串:
function toDigits(number) {
var left;
var results = [];
while (true) {
left = number % 10;
results.unshift(left);
number = (number - left) / 10;
if (number === 0) {
break;
}
}
return results;
}
回答by Attersson
And the easiest.... num_string.split('').map(Number)
而最简单的...... num_string.split('').map(Number)
Try below:
试试下面:
console.log((''+123).split('').map(Number))