8个常用的JavaScript数组方法

数组(Array)是JavaScript中内置的全局对象,在构建诸如商品列表等组件(Component)时,时常用到。

除了常见的push、pop、indexOf等方法,js还提供了一些诸如过滤、规约等流处理方法,非常类似于Java的Stream库。

const students = [    { name: 'Alice', score: 100 },    { name: 'Bob', score: 90 },    { name: 'Trunp', score: 80 },    { name: 'Biden', score: 70 },    { name: 'Joe', score: 60 },    { name: 'Sunshine', score: 50 },    { name: 'Elon', score: 40 },    { name: 'Jack', score: 30 },];

1、filter

过滤方法,返回符合条件的元素。

//返回成绩大于75的高分学生const highScores = students.filter(stu => stu.score > 75);console.log(highScores);

结果:

[    { name: 'Alice', score: 100 },    { name: 'Bob', score: 90 },    { name: 'Trunp', score: 80 }]

更好的是,由于const类型的值,都是不可变量,因此这些操作的返回的都是一个新对象,并不会影响到原值。

2、map

将数组内的item转化成另一种对象,类似于Java的Fucntion<T,R>接口。

//返回全部对象的name属性const names = students.map(stu => stu.name);console.log(names);

结果:

[ 'Alice','Bob', 'Trunp','Biden','Joe', 'Sunshine','Elon','Jack']

3、find

类似于filter方法,但返回第一个符合条件的元素。filter返回一个数组,find返回一个object。

//返回name长度为4的第一个对象const foundedOne = students.find(stu=>stu.name.length === 4);console.log(foundedOne);

结果:

{ name: 'Elon', score: 40 }

由结果可见,虽然elon和jack都符合条件,但只返回了elon。

4、forEach

遍历数组内全部元素。

//打印元素students.forEach(item=>console.log(`stu-name=${item.name},stu-score=${item.score}`));

结果:

stu-name=Alice,stu-score=100stu-name=Bob,stu-score=90stu-name=Trunp,stu-score=80stu-name=Biden,stu-score=70stu-name=Joe,stu-score=60stu-name=Sunshine,stu-score=50stu-name=Elon,stu-score=40

5、some

当数组中有一个符合条件,则返回true,否则返回false。

//是否至少有一个name为Jack的const isSome = students.some(item=>item.name === 'Jack');console.log(isSome);

结果:true

6、every

功能类似于some,但要求每一个元素都符合条件才返回true。

//是否score都大于70const isEvery = students.every(item=>item.score > 70);console.log(isEvery);

结果:false

7、reduce

规约函数。在MDN中给出的API可以简化为,reduce(callback(accumulator,current),initValue)。它有两个参数,第一个是回调函数,第二个initValue是初始值,可选的。current表示数组内的元素,即当前值。

值得一说的是accumulator这个参数,它是中间态的值,一个累加器。换句话数,reduce函数是有状态的,即非纯函数,在多线程执行的时候,需要做一致性处理,否则可能会得到意外值。当然JavaScript是单线程执行的,所以可不考虑,但是用到类似于Java的语言中则需小心。

//求取全部score之和const result = students.reduce(    (accumulator, current) => accumulator + current.score,    0);console.log(result);

以上函数中,我们通过accumulator加上每一个元素值,获得最终结果。

结果:520。

8、includes

是否包含指定的元素值。

const isIncludes = students.includes({ name: 'Jack', score: 30 });console.log(isIncludes);

结果:false。

虽然提供了和最后一个元素的一摸一样的{name: 'Jack', score: 30},但仍然返回false,说明两个对象不是指向同一个引用。

以上,都是很实用的方法,他们使得原来需要很多语句才能做的事情,通过一个简单的调用,即可得出结果。

本文完~

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值