8个常用的JavaScript数组方法

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 }]
2、map
//返回全部对象的name属性const names = students.map(stu => stu.name);console.log(names);
[ 'Alice','Bob', 'Trunp','Biden','Joe', 'Sunshine','Elon','Jack']
3、find
//返回name长度为4的第一个对象const foundedOne = students.find(stu=>stu.name.length === 4);console.log(foundedOne);
{ name: 'Elon', score: 40 }
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
//是否至少有一个name为Jack的const isSome = students.some(item=>item.name === 'Jack');console.log(isSome);
6、every
//是否score都大于70const isEvery = students.every(item=>item.score > 70);console.log(isEvery);
7、reduce
//求取全部score之和const result = students.reduce((accumulator, current) => accumulator + current.score,0);console.log(result);
8、includes
const isIncludes = students.includes({ name: 'Jack', score: 30 });console.log(isIncludes);

评论
