8个常用的JavaScript数组方法
web前端开发
共 2482字,需浏览 5分钟
·
2020-12-08 01:30
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=100
stu-name=Bob,stu-score=90
stu-name=Trunp,stu-score=80
stu-name=Biden,stu-score=70
stu-name=Joe,stu-score=60
stu-name=Sunshine,stu-score=50
stu-name=Elon,stu-score=40
5、some
//是否至少有一个name为Jack的
const isSome = students.some(item=>item.name === 'Jack');
console.log(isSome);
6、every
//是否score都大于70
const 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);
评论