1

In JAVASCRIPT can each number from one variable be copied and transferred to another variable? for example:

var number = 2456;

Can you copy numbers from this variable (2, 4, 5 and 6) and each of them place in a new variable?

for example:

var a = 2;
var b = 4;
var c = 5;
var d = 6;
2
  • 1
    2456 is a single number. Numbers are represented as base 2 floating-point values. You can of course use the / and % operators to extract decimal digits from the value. Commented Feb 18, 2016 at 14:28
  • By number, the question obviously means digit. Commented Feb 18, 2016 at 14:36

2 Answers 2

2

I think it would be better to use an array instead of new variables. If so you can do this

var number = 2456,
    numbers = number.toString().split('').map(function(numberString){
       return Number(numberString);
    });
Sign up to request clarification or add additional context in comments.

2 Comments

There is no need for parseInt here. Use Number instead.
Without new! That will return a number object instead of a primitive value.
1

You can use this function :

var num = 123456;
NumberToArray(num);
alert(a);
alert(b);
alert(c);
alert(d);
function NumberToArray(num)
{
    var result = [];
    function div(val, by){  
        return (val - val % by) / by; 
    } 
    while (num != 0)
    {
        result.unshift(num%10);
        num = div(num, 10);
    }
    for (var i=0; i<result.length; i++)
    {
        window[String.fromCharCode(97+i)] = result[i]
    }
}

2 Comments

are you sure this works , when i try to open it in chrome blank page appears?
@silver, yep, because he used the array.shift method :-) array.unshift needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.