Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map numbers String to Array of numbers

I can't see why this code doesn't produce numbers. Can anyone explain please?

a = '1 3 2 6 1 2'.split(' ');
a = a.map(Number);

for (item in a){
    console.log(typeof(item));
}

The output for me in Chrome is 6 strings.

like image 355
Robin Andrews Avatar asked Sep 22 '16 17:09

Robin Andrews


People also ask

How do you convert a string of numbers to an array of numbers?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.

Can I use map on an array of objects?

map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array.


1 Answers

You need to use for..of, not for..in to iterate Arrays:

arr = '1 2 3 4'.split(' ').map(Number) // ["1","2","3","4"] => [1,2,3,4]

for( item of arr ) console.log( typeof(item), item )
like image 138
vsync Avatar answered Oct 11 '22 17:10

vsync