If I have a variable
var number = 123
how can I split it into an array like this?
[0]=1
[1]=2
[2]=3
I know there is a string split but what about variables?
If I have a variable
var number = 123
how can I split it into an array like this?
[0]=1
[1]=2
[2]=3
I know there is a string split but what about variables?
You can convert your number to a string
, then use split()
on it, then map it back to numbers like this:
var num = 123; // 123
var str = num.toString(); // "123"
var arr = str.split(''); // ["1", "2", "3"]
var numberArr = arr.map(Number); // [1, 2, 3]
If you want to get really cheeky you can do this, since strings are indexed in an array-like fashion.
function splitNum(num) {
return Array.prototype.map.call(num.toString(), Number);
}
var num = splitNum(555); // >> [5, 5, 5]
var number = 123;
var temp;
number = number.toString();
for (var i = 0; i < number.length; i++)
{
temp = number[i];
number[i] = number[number.length - 1 - i];
number[number.length - 1 - i] = temp;
}
console.log(number[0]);
console.log(number[1]);
console.log(number[2]);