一、for 循环
for (let i = 0; i < 5; i++) {
console.log(i);
}
二、forEach 方法
const array = [1, 2, 3, 4, 5];
array.forEach(function(el, index, arr) {
console.log(el, index, arr);
});
三、for…of 循环(ES6)
const array = [1, 2, 3, 4, 5];
for (const el of array) {
console.log(el);
}
四、map
const array = [1, 2, 3, 4, 5];
const newArray = array.map(function(item, index, arr) {
return item* 2;
});
console.log(newArray);
五、filter
const array = [1, 2, 3, 4, 5];
const filteredArray = array.filter(function(item, index, arr) {
return item> 3;
});
console.log(filteredArray);
六、reduce
const array = [1, 2, 3, 4, 5];
const sum = array.reduce(function(accumulator, item, index, arr) {
return accumulator + item;
}, 0);
console.log(sum);
七、Object.keys() (遍历对象的键)
const obj = {a: 1, b: 2, c: 3};
for (const key of Object.keys(obj)) {
console.log(key);
}
八、Object.values() (遍历对象的值)
const obj = {a: 1, b: 2, c: 3};
for (const key of Object.values(obj)) {
console.log(key);
}
九、Object.entries 对象键值对
const obj = {a: 1, b: 2, c: 3};
for (const key of Object.entries(obj)) {
console.log(key);
}