why does this split function work by concatenating "" to a number in javascript?

0

I am doing a function to convert from binary to decimal and I needed to cut the entered number, and I got this question:

link

In it they explain that if you have an example number

var numero = 123456;

And you apply split () to get 1,2,3,4,5,6

var numero2=numero.split("");
var numero3=numero.splt();

It will not work.

But if you concatenate "" with the number:

var numero3=(""+numero);
var numero4=numero3.split("");

Returns 1,2,3,4,5,6

Why this works?

    
asked by Victor Alvarado 06.05.2017 в 16:15
source

2 answers

4

Because split() is a unique function for data of type String, and in your first two examples the variable numero is an Integer, so it will not work what you want to do.

var numero = 123456; //Dato de tipo Integer
var numero2=numero.split(""); //Error porque numero es de tipo entero
var numero3=numero.split(); //Error porque numero es de tipo entero

In your second example it works because when you do this concatenation ""+numero your variable numero3 becomes a String with value "123456" that's why when calling split() it does not send you an error.

var numero3=(""+numero); // Aquí tu variable numero3 es String
var numero4=numero3.split(""); // Ok split()
    
answered by 06.05.2017 / 16:20
source
1

split () is a function to work with Strings. If you have:

var numero = 123456;

What you have is an integer, but when concatenating "" + 123456 , what you do is concatenate with a String and convert to String, now if you can cut with split ()

You can try the following in the browser console:

console.log( typeof( 123456 ));
console.log( typeof( "" + 123456 ));
console.log( typeof( 123456 + "" ));

The result will be:

number
string
string
    
answered by 06.05.2017 в 17:21