简体   繁体   中英

How can I separate whole javaScript numbers and multiply them separately

What I am trying to do is to separate whole numbers like 1986 or 364 and to add them to array like [1000, 900, 80, 6] or [300, 60, 4], it doesn't matter how big or small is number.

function convert(num) {
   var numbers = String(num).split("");
   var times = [1000, 100, 10, 1];
   var converted = [];
   for(var i = 0; i < numbers.length; i++){
       converted.push(numbers[i] * times[times.length - numbers.length + i]);   
   }
   return converted;
}

convert(360);

It will work for any number of digits

 function convert(num) { var temp = num.toString(); var ans = []; for (var i = 0; i < temp.length; i++) { //get the ith character and multiply with correspondng powers of 10 ans.push(parseInt(temp.charAt(i)) * Math.pow(10, temp.length - i - 1)); } return ans; } convert(39323680); 

As @James Thorpe mentioned, you need to define whats better for you, but this seems to be tidier, and supports any number (not only 4 digits)

 function seperateNumber(num) { var seperated = []; while (num > 0) { var mod = num % 10; seperated.push(mod); num = (num - mod) / 10; } return seperated; } console.log(seperateNumber(1986)); 

Are you asking what if you want convert a higher number?

You could try something like this (not very elegant though):

 function convert(num) { var numbers = String(num).split(""); converted = []; numbers.reverse(); numbers.forEach(function(element, index) { converted.push(element*Math.pow(10,index)); }); return converted.reverse(); } console.log(convert(19813)); 

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