Robin Andrews
Robin Andrews

Reputation: 3804

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.

Upvotes: 6

Views: 10069

Answers (4)

Lova Chittumuri
Lova Chittumuri

Reputation: 3323

Below code will be helpful.

var num = 343532;
 var result=num.toString().split('').map(Number);
 console.log(result);

Upvotes: 0

vsync
vsync

Reputation: 130471

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 )

Upvotes: 1

jsquerylover
jsquerylover

Reputation: 56

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

console.log(a);

Upvotes: 0

Hugo Migneron
Hugo Migneron

Reputation: 4907

You are not iterating over the content of a as you seem to be expecting but are instead iterating on the indexes in your for..in loop.

You can refer to the for..in documentation here. Interesting area is where they talk about using for..in on Arrays (and how you probably shouldn't in a case like this).

If I understand correctly this is what I believe will produce the result you are expecting :

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

Similarly, to access the elements directly

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

Upvotes: 0

Related Questions