JS数组遍历的方法

数组遍历的方法

方法是否改变原数组特点
forEach()数组方法,不改变原数组,没有返回值
map()数组方法,不改变原数组,有返回值
filter()数组方法,过滤数组,返回包含符合条件的元素组成的数组
for…offor…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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值