JavaScript 数字拆分为单独的数字

发布于 2024-12-09 20:15:32 字数 313 浏览 0 评论 0原文

我正在尝试解决一个数学问题,其中我取一个数字,例如 45111,然后将数字拆分为单独的数字,例如 4 51 1 1。然后我会将每个数字保存到一个 var 中以运行方法。有谁知道如何将数字拆分为单独的数字?

例如,我有一个在数组上运行的循环:

for (var i = 0; i < range.length; i++) {
  var n = range[i];
}

对于每个数字,我想分割它的数字并将它们加在一起?

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

半仙 2024-12-16 20:15:32
var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);

var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);

半世晨晓 2024-12-16 20:15:32
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]
 */ 

更新:计算总和

for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);

/*
 * Outputs: 39
 */
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
 */
惯饮孤独 2024-12-16 20:15:32

您还可以以“数学”方式完成此操作,而不将数字视为字符串:

var num = 278;
var digits = [];
while (num != 0) {
    digits.push(num % 10);
    num = Math.trunc(num / 10);
}
digits.reverse();
console.log(digits);

我看到的一个好处是,您不必对每个数字都运行 parseInt(),您可以将实际数字作为数值进行处理。

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 = Math.trunc(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.

放飞的风筝 2024-12-16 20:15:32

这是我发现的最短的,尽管它确实以字符串形式返回数字:

let num = 12345;

[...num+''] //["1", "2", "3", "4", "5"]

或者使用它来返回整数:

[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]

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]
月亮是我掰弯的 2024-12-16 20:15:32

我将提供已经给出的答案的变体,以便您可以看到一种始终保留数字类型的不同方法:

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

在将数字转换为罗马数字时,我使用了诸如上述的技术,效果良好,这是其中之一我最喜欢的开始学习我不熟悉的编程语言的方法。例如,在世纪之交之后,我设计了一种使用 Tcl 将数字转换为罗马数字的方法: http://code.activestate.com/recipes/68379-conversion-to-roman-numerals/

我的 Tcl 脚本中的类似行是:

  while {$arabic} {
    set digit [expr {$arabic%10}]
    set arabic [expr {$arabic/10}]

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/

The comparable lines in my Tcl script being:

  while {$arabic} {
    set digit [expr {$arabic%10}]
    set arabic [expr {$arabic/10}]
灰色世界里的红玫瑰 2024-12-16 20:15:32
// 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]

// 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]

冧九 2024-12-16 20:15:32

使用 Stringsplitmap

String(number).split("").map(Number);

function splitNum(num) {
    return String(num).split("").map(Number);
}

console.log(splitNum(1523)); // [1, 5, 2, 3]
console.log(splitNum(2341)); // [2, 3, 4, 1]
console.log(splitNum(325)); // [3, 2, 5]

Use String, split and map :

String(number).split("").map(Number);

function splitNum(num) {
    return String(num).split("").map(Number);
}

console.log(splitNum(1523)); // [1, 5, 2, 3]
console.log(splitNum(2341)); // [2, 3, 4, 1]
console.log(splitNum(325)); // [3, 2, 5]

夜深人未静 2024-12-16 20:15:32

您可以使用字符串而不是数字来实现此目的。您可以这样做

(111 + '').split('')

这将返回一个字符串数组 ['1','1','1'] ,您可以对其进行迭代并调用 parseInt 方法。

parseInt('1') === 1

如果你想要各个数字的总和,你可以使用reduce函数(从Javascript 1.8实现),如下所示

(111 + '').split('').reduce(function(previousValue, currentValue){  
  return parseInt(previousValue,10) + parseInt(currentValue,10);  
})

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.

parseInt('1') === 1

If you want the sum of individual digits, you can use the reduce function (implemented from Javascript 1.8) like this

(111 + '').split('').reduce(function(previousValue, currentValue){  
  return parseInt(previousValue,10) + parseInt(currentValue,10);  
})
2024-12-16 20:15:32

不转换为字符串:

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

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;
}
书信已泛黄 2024-12-16 20:15:32

使用 String...map

const num = 7890;

const digits = [...String(num)].map(Number);

console.log(digits)

或者,使用 ...reduce 来获取数字及其总和。

const sumOfDigits = num => [...""+num].reduce((acc, dig) => acc + +dig, 0);

console.log('Sum of digits: ', sumOfDigits(7890));

Using String, ... and map

const num = 7890;

const digits = [...String(num)].map(Number);

console.log(digits)

Alternatively, using ... and reduce to get digits and their sum.

const sumOfDigits = num => [...""+num].reduce((acc, dig) => acc + +dig, 0);

console.log('Sum of digits: ', sumOfDigits(7890));

池予 2024-12-16 20:15:32

将每 2 个参数分开。

function separator(str,sep) {
    var output = '';
    for (var i = str.length; i > 0; i-=2) {
        var ii = i-1;
        if(output) {
            output = str.charAt(ii-1)+str.charAt(ii)+sep+output;
        } else {
            output = str.charAt(ii-1)+str.charAt(ii);
        }            
    }
    return output;
}
console.log(separator('123456',':')); //Will return 12:34:56

Separate each 2 parametr.

function separator(str,sep) {
    var output = '';
    for (var i = str.length; i > 0; i-=2) {
        var ii = i-1;
        if(output) {
            output = str.charAt(ii-1)+str.charAt(ii)+sep+output;
        } else {
            output = str.charAt(ii-1)+str.charAt(ii);
        }            
    }
    return output;
}
console.log(separator('123456',':')); //Will return 12:34:56
情话难免假 2024-12-16 20:15:32

对递归的有趣介绍。该答案接受一个 Number 并返回一个 Number 数字数组。它不会将数字转换为字符串作为中间步骤。

给定 n = 1234

  • n % 10 将返回第一个(右润)数字,4
  • n / 10将返回 123 并带有一些余数
  • 使用 Math.floor 我们可以去掉余数
  • 重复这些步骤,我们可以形成整个结果

现在我们只需要构建递归条件,

  • 如果号码已经单个数字 (n < 10),返回该数字的数组单例
  • ,否则(归纳)数字为 10 或更大;重复并附加到第一个数字
const digits = (n = 0) =>
  n < 10
    ? [ n ]
    : [ ... digits (Math.floor (n / 10)), n % 10 ]

console.log (digits ())        // [ 0 ]
console.log (digits (1))       // [ 1 ]
console.log (digits (12))      // [ 1, 2 ]
console.log (digits (123))     // [ 1, 2, 3 ]
console.log (digits (11234))   // [ 1, 2, 3, 4 ]

console.log (digits (123456789012))
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 ]

A fun introduction to recursion. This answer takes a Number and returns an array of Number digits. It does not convert the number to a string as an intermediate step.

Given n = 1234,

  • n % 10 will return first (right-moist) digit, 4
  • n / 10 will return 123 with some remainder
  • Using Math.floor we can chop the remainder off
  • Repeating these steps, we can form the entire result

Now we just have to build the recursion condition,

  • If the number is already a single digit (n < 10), return an array singleton of the digit
  • otherwise (inductive) the number is 10 or greater; recur and prepend to the first digit

const digits = (n = 0) =>
  n < 10
    ? [ n ]
    : [ ... digits (Math.floor (n / 10)), n % 10 ]

console.log (digits ())        // [ 0 ]
console.log (digits (1))       // [ 1 ]
console.log (digits (12))      // [ 1, 2 ]
console.log (digits (123))     // [ 1, 2, 3 ]
console.log (digits (11234))   // [ 1, 2, 3, 4 ]

console.log (digits (123456789012))
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 ]

我喜欢麦丽素 2024-12-16 20:15:32

对于 ES6,您可以使用 Array .from ,字符串数字为 可迭代Number 作为映射函数。

const getDigits = n => Array.from(n.toString(), Number);

console.log(getDigits(12345));

With ES6, you could use Array.from with a stringed number as iterables and Number as mapping function.

const getDigits = n => Array.from(n.toString(), Number);

console.log(getDigits(12345));

眼泪都笑了 2024-12-16 20:15:32

这也有效:

var number = 12354987;
console.log(String(number).split('').map(Number));

This also works:

var number = 12354987;
console.log(String(number).split('').map(Number));

尾戒 2024-12-16 20:15:32

影子向导,Orien 的扩展版本

var num:Number = 1523;
var digits:Array = [];
var cnt:int = 0;
while (num > 0) {
    var mod:int = num % 10;
    digits.push(mod * Math.pow(10, cnt))

    num = Math.floor(num / 10);
    cnt++;
}
digits.reverse();
trace(digits);

输出:1000,500,20,3

Shadow Wizard , extended version by Orien

var num:Number = 1523;
var digits:Array = [];
var cnt:int = 0;
while (num > 0) {
    var mod:int = num % 10;
    digits.push(mod * Math.pow(10, cnt))

    num = Math.floor(num / 10);
    cnt++;
}
digits.reverse();
trace(digits);

output:1000,500,20,3

泪意 2024-12-16 20:15:32

我用了这个简单的方法来做到这一点。

分割数字

var N = 69;
var arr = N.toString().split('').map(Number)
// outputs [6,9]
console.log( arr ); 

将它们加在一起

console.log(arr.reduce( (a,b) => a+b )); // 15

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
私野 2024-12-16 20:15:32

最简单的...... num_string.split('').map(Number)

尝试以下:

console.log((''+123).split('').map(Number))

And the easiest.... num_string.split('').map(Number)

Try below:

console.log((''+123).split('').map(Number))

甜是你 2024-12-16 20:15:32

为了以相同的顺序将整数拆分为各个数字,我使用并更喜欢正则表达式,因为它可以防止丢失数字的标识,即使它们已转换为字符串也是如此。

以下代码行将整数转换为字符串,使用正则表达式匹配字符串内的任何单个数字并返回这些数字的数组,然后将该数组映射为转换回数字。

const digitalize = n =>; String(n).match(/\d/g).map(Number);

To just split an integer into its individual digits in the same order, Regular Expression is what I used and prefer since it prevents the chance of loosing the identity of the numbers even after they have been converted into string.

The following line of code convert the integer into a string, uses regex to match any individual digit inside the string and return an array of those, after which that array is mapped to be converted back to numbers.

const digitize = n => String(n).match(/\d/g).map(Number);

今天小雨转甜 2024-12-16 20:15:32

我发布这个答案是为了介绍 unshift 的使用,这是一种现代解决方案。使用push,您可以添加到数组的末尾,而 unshift 可以添加到开头。这使得数学方法更加强大,因为您不再需要逆向。

let num = 278;
let digits = [];
while (num > 0) {
    digits.unshift(num % 10);
    num = parseInt(num / 10);
}
console.log(digits);

I am posting this answer to introduce the use of unshift which is a modern solution. With push, you add to the end of an array while unshift adds to the beginning. This makes the mathematical approach more powerful as you won't need to reverse anymore.

let num = 278;
let digits = [];
while (num > 0) {
    digits.unshift(num % 10);
    num = parseInt(num / 10);
}
console.log(digits);

别念他 2024-12-16 20:15:32

并作为一个班轮。

console.log(BigInt(1e200).toString().split('').reduce((pv, v) => Number(v) + pv, 0));

And as a one liner.

console.log(BigInt(1e200).toString().split('').reduce((pv, v) => Number(v) + pv, 0));

攒一口袋星星 2024-12-16 20:15:32
var num = 111,
 separateDigits = num.toString().split(""), i, l = separateDigits.length;

for( i = 0; i < l; ++i ) {
someObject.someMethod( +separateDigits[i] );
}
var num = 111,
 separateDigits = num.toString().split(""), i, l = separateDigits.length;

for( i = 0; i < l; ++i ) {
someObject.someMethod( +separateDigits[i] );
}
溺孤伤于心 2024-12-16 20:15:32

number 获取数字的函数方法是从 number 获取 string,将其拆分为 数组 (字符)并将每个元素映射回数字。

例如:

var number = 123456;

var array = number.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
});

console.log(array); // returns [1, 2, 3, 4, 5, 6]

如果您还需要对所有数字求和,则可以附加 reduce() 方法到前面的代码:

var num = 123456;

var array = num.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
})
.reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
}, 0);

console.log(array); // returns 21

作为替代方案,使用 ECMAScript 2015(第 6 版),您可以使用 箭头函数

var number = 123456;
var array = number.toString().split('').map((item, index) => parseInt(item));
console.log(array); // returns [1, 2, 3, 4, 5, 6]

如果您需要对所有数字求和,您可以将 reduce() 方法附加到前面的代码中:

var num = 123456;

var result = num.toString()
.split('')
.map((item, index) => parseInt(item))
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

console.log(result); // returns 21

A functional approach in order to get digits from a number would be to get a string from your number, split it into an array (of characters) and map each element back into a number.

For example:

var number = 123456;

var array = number.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
});

console.log(array); // returns [1, 2, 3, 4, 5, 6]

If you also need to sum all digits, you can append the reduce() method to the previous code:

var num = 123456;

var array = num.toString()
.split('')
.map(function(item, index) {
   return parseInt(item);
})
.reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
}, 0);

console.log(array); // returns 21

As an alternative, with ECMAScript 2015 (6th Edition), you can use arrow functions:

var number = 123456;
var array = number.toString().split('').map((item, index) => parseInt(item));
console.log(array); // returns [1, 2, 3, 4, 5, 6]

If you need to sum all digits, you can append the reduce() method to the previous code:

var num = 123456;

var result = num.toString()
.split('')
.map((item, index) => parseInt(item))
.reduce((previousValue, currentValue) => previousValue + currentValue, 0);

console.log(result); // returns 21
昇り龍 2024-12-16 20:15:32

你可以试试这个。

  var num = 99;

  num=num.toString().split("").map(value=>parseInt(value,10)); //output [9,9]

希望这有帮助!

You can try this.

  var num = 99;

  num=num.toString().split("").map(value=>parseInt(value,10)); //output [9,9]

Hope this helped!

哭了丶谁疼 2024-12-16 20:15:32
function iterateNumber(N, f) {
    let n = N;
    var length = Math.log(n) * Math.LOG10E + 1 | 0;
    for (let i = 0; i < length; i++) {
        const pow = Math.pow(10, length - i - 1)
        let c = (n - (n % pow)) / pow
        f(c, i)
        n %= pow
    }
}
function iterateNumber(N, f) {
    let n = N;
    var length = Math.log(n) * Math.LOG10E + 1 | 0;
    for (let i = 0; i < length; i++) {
        const pow = Math.pow(10, length - i - 1)
        let c = (n - (n % pow)) / pow
        f(c, i)
        n %= pow
    }
}
将军与妓 2024-12-16 20:15:32

('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45

true

或没有地图

('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45

正确

('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45

true

or without map

('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45

true

层林尽染 2024-12-16 20:15:32

您可以在单行中完成,将每个数字分开,然后将它们加在一起:

var may = 12987;
var sep = (""+may).split("").map(n=>+n).reduce((a,b)=>a+b);

You can do it in single line, seperate each digits than add them together :

var may = 12987;
var sep = (""+may).split("").map(n=>+n).reduce((a,b)=>a+b);
神仙妹妹 2024-12-16 20:15:32

这是我的简短解决方案..带有数字总和

    function sum (num) {
    let sNumber = num
        .toString()
        .split('')
        .reduce((el1, el2) => {
            return Number(el1) + Number(el2)
        }, 0)
        return sNumber
     }

console.log(sum(123))
控制台.log(总和(456))

This is my short solution.. with sum of number

    function sum (num) {
    let sNumber = num
        .toString()
        .split('')
        .reduce((el1, el2) => {
            return Number(el1) + Number(el2)
        }, 0)
        return sNumber
     }

console.log(sum(123))
console.log(sum(456))

撩人痒 2024-12-16 20:15:32

javascript有一个函数,你可以很容易地使用它。

console.log(new Intl.NumberFormat().format(number));

例如 :

console.log(new Intl.NumberFormat().format(2334325443534));
==> 2,334,325,443,534

javascript has a function for it and you can use it easily.

console.log(new Intl.NumberFormat().format(number));

for example :

console.log(new Intl.NumberFormat().format(2334325443534));
==> 2,334,325,443,534
故事↓在人 2024-12-16 20:15:32

我可能是错的,但解决方案是零碎的。也许,正如我仍在学习的那样,这些函数在同一个函数中可以做很多事情。请随时纠正我。

const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);

因此,我们将参数转换为 and arr,并添加空格。我们对每个元素都进行这样的操作,并使用 map 方法将其推送到一个新数组中。分割后,我们使用reduce对所有元素求和并得到总数。

正如我所说,如果您看到我没有看到的内容,请毫不犹豫地纠正我或改进功能。

差点忘了,以防万一:

const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);

如果负数或只是简单的零作为参数下降。祝我们大家编码愉快。

I might be wrong, but a solution picking up bits and pieces. Perhaps, as I still learning, is that the functions does many things in the same one. Do not hesitate to correct me, please.

const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);

So we take the parameter and convert it to and arr, adding empty spaces. We do such operation in every single element and push it into a new array with the map method. Once splited, we use reduce to sum all the elements and get the total.

As I said, don't hesitate to correct me or improve the function if you see something that I don't.

Almost forgot, just in case:

const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);

If negatives numbers or just plain zero go down as parameters. Happy coding to us all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文