简体   繁体   中英

Retrieving Digits into an Array - JavaScript

I am doing a JavaScript, trying to retrieve the user's numerical input, and store the input's digits as an array.

I managed to retrieve the user's input using DOM, but, how can I store the digits into an array?

If you want to obtain an array of numbers , one solution is to use Array.from method and map array items to numbers.

 let number=1234; let array=Array.from(number.toString()).map(Number); console.log(array); 

If you want to store singular digits, you could use .split('')

 userInput = '42'; console.log(userInput.split('')); 

what you can do here is simply:

userInput1 = '42';
userInput2 = '43';
const inputArray = [userInput1, userInput2]

For an array of number:

 var input = "123456789"; var array = input.split('') for(var i = 0; i <array.length; i++) { array[i] = +array[i]; } console.log(array) 

The operation +array[i] is just a quick way to do the number conversion.

If you want the array of chars remove the for loop from the code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM