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