1

How do I get the data (not index) in this loop? l gives me the index, but I need the data.

this.letters = ['a','b','c','d'];
this.arr = [];
for (let l in this.letters) {
    this.arr.push(l);
}

3 Answers 3

3

Simply change from for ... in ... to for ... of ... as follows:

this.letters = ['a','b','c','d'];
this.arr = [];
for (let l of this.letters) {
    this.arr.push(l);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The answer posted by Benny is correct that using a for..of loop will allow you to iterate over an array only getting the items in an array and not also the properties of the array object.

That being said, if you're looking to copy an array, you can simply use the slice function with no parameters to make a copy of the array.

const letters = ['a','b','c','d'];
const arr = letters.slice();

Note that slice makes a copy of the array, it does not make copies of the items in the array. This is important if you're dealing with objects in the array and not strings and such. It means that if you modify an item in the copied array, the corresponding item in the original array will be modified as well (and vice-versa).

enter image description here

Here's the MDN docs on slice(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Oh, and as a bonus tidbit, you can also use the array spread operator (...) to accomplish making a copy of an array. I prefer to use slice, though as it feels more readable to me, but to each their own.

enter image description here

Comments

0

I found the answer:

this.letters = ['a','b','c','d'];
this.arr = [];
for( let i in this.letters) {
  if (this.letters.hasOwnProperty(l)) {
    this.todos.push(this.letters[l]);
  }
}

1 Comment

The other answer to this question will do this for you. The for...of loop is the correct way to do this in ES2015+. That being said, there's an easier way to do what you're doing in your code. I'll post an answer.

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.