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.
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 )
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]);
}
a = '1 3 2 6 1 2'.split(' ');
a = a.map(Number);
console.log(a);
itemare the indexes, not the values. You probably meantfor (item of a).itemdirectly to verify that you iterate over the values, log the whole arraya(there should be a distinction in color for strings and numbers), verify if afor-inloop iterates over values or indexes via the docs.