6

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.

3
  • 10
    item are the indexes, not the values. You probably meant for (item of a). Commented Sep 22, 2016 at 17:13
  • Spot on. Thanks. I would mark you answer as the solution but it's only a comment... Commented Sep 22, 2016 at 17:16
  • Not sure whether it’s right to answer your question… it’s almost off-topic for being a simple typo (or a “mental” typo). Here are a few things you should have done before asking your question: log item directly to verify that you iterate over the values, log the whole array a (there should be a distinction in color for strings and numbers), verify if a for-in loop iterates over values or indexes via the docs. Commented Sep 22, 2016 at 17:25

4 Answers 4

1

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 )

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
}

Comments

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

console.log(a);

1 Comment

you were trying to use typeof item which is string because a is object in your case.
0

Below code will be helpful.

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

Comments

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.