ES6中遍歷數組的方法有以下幾種:
const arr = [1, 2, 3];
for (let element of arr) {
console.log(element);
}
const arr = [1, 2, 3];
arr.forEach(function(element) {
console.log(element);
});
const arr = [1, 2, 3];
const newArr = arr.map(function(element) {
return element * 2;
});
console.log(newArr); // [2, 4, 6]
const arr = [1, 2, 3, 4, 5];
const newArr = arr.filter(function(element) {
return element % 2 === 0;
});
console.log(newArr); // [2, 4]
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 15
const arr = [1, 2, 3, 4, 5];
const result = arr.find(function(element) {
return element > 3;
});
console.log(result); // 4
const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex(function(element) {
return element > 3;
});
console.log(index); // 3
const arr = [1, 2, 3, 4, 5];
const result = arr.some(function(element) {
return element > 3;
});
console.log(result); // true
const arr = [1, 2, 3, 4, 5];
const result = arr.every(function(element) {
return element > 0;
});
console.log(result); // true