数组遍历的方法
方法 | 是否改变原数组 | 特点 |
---|---|---|
forEach() | 否 | 数组方法,不改变原数组,没有返回值 |
map() | 否 | 数组方法,不改变原数组,有返回值 |
filter() | 否 | 数组方法,过滤数组,返回包含符合条件的元素组成的数组 |
for…of | 否 | for…of遍历具有Iterator迭代器的对象的属性,返回的是数组的元素、对象的属性值,不能遍历普通的obj对象,将异步循环变成同步循环 |
every() 和 some() | 否 | 数组方法,some()只要有一个是true,便返回true;而every()只要有一个是false,便返回false. |
find() 和 findIndex() | 否 | 数组方法,find()返回的是第一个符合条件的值;findIndex()返回的是第一个符合条件的值的索引值 |
reduce() 和 reduceRight() | 否 | 数组方法,reduce()对数组正序操作;reduceRight()对数组逆序操作 |
forEach()
const arr = ["hello", 'world', '!'];
arr.forEach(item => {
console.log(item);
});
hello
world
!
map()
const arr = ["hello", 'world', '!'];
const arr2 = arr.map(item => {
console.log(item);
return item;
});
console.log(arr2);
hello
world
!
[ 'hello', 'world', '!' ]
filter()
const arr = ["hello", 'world', '!'];
const arr2 = arr.filter(item => {
return item !== '!';
});
console.log(arr2);
[ 'hello', 'world' ]
for…of
const arr = ["hello", 'world', '!']
for (const item of arr) {
console.log(item);
}
hello
world
!
every() 和 some()
every()
const arr = ["hello", 'world', '!'];
const result = arr.every(item => {
return item === '!'
});
console.log(result);
false
some()
const arr = ["hello", 'world', '!'];
const result = arr.some(item => {
return item === '!'
});
console.log(result);
true
find() 和 findIndex()
find()
const arr = ["hello", 'world', '!'];
const result = arr.find(item => {
return item.includes('o');
});
console.log(result);
hello
findIndex()
const arr = ["hello", 'world', '!'];
const result = arr.findIndex(item => {
return item.includes('d');
});
console.log(result);
1