종우의 컴퓨터 공간
General loops 본문
forEach
const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];
cars.forEach(function(car, index, array) { //takes three params
console.log(`${index} : ${car}`);
console.log(array);
});
- it is used to loop through the array
- forEach takes the anonymous function with three parameters
- it is much cleaner over normal for loop
map
const users = [
{id:1, name:'John'},
{id:2, name:'Sara'},
{id:3, name:'James'}
];
const ids = users.map(function(user) {
return user.id;
});
console.log(ids); //yields [1, 2, 3]
- it is used to loop through the array with objects in it
- map takes the anonymous function with one parameter of each object in the array
- 'return' is used to populate the needed data
for in
const user = {
firstName: 'John',
lastName: 'Doe',
age: 40
}
for(let x in user) {
console.log(`${x} : ${user[x]}`); //x yields each key of the object
}
- it is used to loop through the object
- in the above example code, x takes each key of the object
'자바 스크립트 (JavaScript) > JavaScript Language Fundamentals' 카테고리의 다른 글
Window Objects (0) | 2021.07.30 |
---|---|
Function Declarations & Expressions (0) | 2021.07.28 |
Switch Statement (0) | 2021.07.28 |
If Statements & Comparison Operators (0) | 2021.07.25 |
Dates & Times (0) | 2021.07.25 |