0

I've come across some strange behavior that I cannot find the root cause of when pushing the contents of one string array to another.

I have one array that I first empty to make room for the new array's values and then I iterate over the new array, pushing its contents to the first emptied array. Here is how the code looks:

oldArray.length = 0;
console.log(newArray);
for (let item in newArray) {
  console.log(item);
  this.oldArray.push(item);
}

The output of the first print is:

["a string", "another string", "a third string"]

The output of each print inside the for loop is:

0, 1, 2

This is where I am lost, I am for some reason getting the indexes of the items instead of the strings themselves. Could it be related to the way in which I am emptying the old array? Note that for this purpose, it's important that I do not mess up the oldArray reference, which I'd prefer to keep intact.

1 Answer 1

4

When you use for( .. in ..), you iterate over the indexes of the array, not the values themselves. To get the value, you could do this:

console.log(newArray[item]);

It's even better to just use the for(.. of ..) loop instead.

for (const item of newArray) {

Aside: use const instead of let for this case.

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

1 Comment

That's exactly it! I was very confused since it seemingly worked in another place, but there I was using 'of' and not 'in'...

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.