1

I was working on a small javascript coding challenge that was simple enough, but ran into a odd bit of strange behavior that I couldn't find documented anywhere. Maybe someone could point me to where it states that this is expected behavior?

myIntegerArray = [1,2,3,4];
b = new Array();

for(var v in a)
{
    b.push(v);
}
console.log(b); // returns ["1","2","3","4"]. Note String result

If I were to use the forEach() however I get an array of Numbers back:

a.forEach(function(element,index,ay)
    {
        b.push(element)
    });
//a console.log(b) will return [1,2,3,4]
2
  • 2
    Your code won't produce that output. The array would be zero-indexed, not one-indexed. Commented Jan 21, 2014 at 4:10
  • Ah, you're right. I looked at my result again and so it is. Should have clued me in, but I was so distracted by the apparent type change that I missed it altogether. Commented Jan 21, 2014 at 4:31

2 Answers 2

4

You're pushing the key name, not the value. You need to to do this:

b.push(a[v]);

This might help you understand:

for (var key in obj) {
  var value = obj[key];
  arr.push(value);
}
Sign up to request clarification or add additional context in comments.

Comments

2
for(var v in a)

In JavaScript, Arrays are just like Objects. for..in loop will get the keys of the Array objects, which are the actual array indices. As we know that, JavaScript Object keys can only be Strings. So, what you are actually getting is, the Array indices in String format.

And another reason why for..in should not be used, is in MDN docs. Quoting from for..in

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.

So, you either use

for(var index = 0; index < array.length; index += 1) {
    array[index];
}

Or the forEach which you have shown in the question itself.

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.