Reputation: 3
new to JS and trying to figure out how to set attributes to elements using a loop. I tried the code below for kicks, and it didn't seem to work:
attArr.forEach((item) => {
element.setAttribute(item, attArr[item]);
});
However, the below works. What gives?
for (const item in attArr) {
element.setAttribute(item, attArr[item]);
}
Upvotes: 0
Views: 658
Reputation: 878
To answer it in a simple way, forEach
will iterate over the items, for...in
will iterate over the keys.
const arr = ['Meat', 'Cheese']
arr.forEach(item => {
console.log(item)
})
# Output 'Meat' 'Cheese'
for(const item in arr){
console.log(item);
}
# Output '0' '1'
Upvotes: 0
Reputation: 372
When you do x in y
You are iterating using keys. And when you do forEach you are calling a function for each item in array y
. What you want to do is probably more like this
Object.keys(attArr).forEach( key => {
element.setAttribute(key,attArr[key]);
});
Upvotes: 1
Reputation: 26
The problem with the first example is that attArr[item]
causes an undefined
.
if you want reply the behaviour of the second example using a foreach, you have to do the following:
attArr.forEach((item, index) => {
element.setAttribute(index, attArr[item]);
});
Upvotes: 0
Reputation: 177950
It would be useful to see the rest of your code.
The for...in
is iterating over object entries
Here is the same using forEach
Object.entries(attArr).forEach(([key,val]) => element.setAttribute(key, val));
Upvotes: 1