8个JavaScript常用操作数组方法

const students = [
  {name: "sam", age: 26, score: 80},
  {name: "john", age: 25, score: 86},
  {name: "dean", age: 20, score: 78},
  {name: "timothy", age: 18, score: 95},
  {name: "frank", age: 21, score: 67}
]

1.map()
作用:允许你获取一个数组并将其转换为一个新数组。在这个中,新数组中的所有项目看起来都略有不同。如果我们想得到每个学生的名字。我们可以通过使用 map() 获取名称数组。

const studentNames = students.map((students) => {
	return students.name
})
console.log(studentNames) //['sam', 'john', 'dean', 'timothy', 'frank']

2.filter()
作用:过滤数组中满足条件的数据。例如过滤出年龄小于或等于24岁的所有学生。

const filteredStudents = students.filter((students) => {
  return students.age <= 24
})
console.log(filteredStudents)

3.includes()
作用:检查指定元素是否在数组中。

const fruits = [ 'mango', 'apple', 'orange', 'pineapple', 'lemon']
const includesApple = fruits.includes('apple')
const includesBananer = fruits.includes('bananer')
console.log(includesApple) // true
console.log(includesBananer ) // false

4.find()
作用:在数组中查找单个对象。例如我们想查找一个叫frank的学生。

const singleStudent = students.find((students) => {
	return students.name === 'frank'
})
console.log(singleStudent); 
/*
Object {
    age: 21,
    name: "frank",
    score: 67
  }
*/

5.forEach()
作用:遍历数组元素。不返回任何内容,因此不需要 return 语句。例如我们需要打印出 student 数组中所有学生的名字。

students.forEach((students) => {
  console.log(students.name)   //sam john  dean  timothy  frank
})

6.some()
作用:检测数组中是否存在满足条件的数据,返回true或false。例如检查这个数组中是否有一些学生是未成年人。

const hasUnderageStudents = students.some((students) => {
   return students.age < 18
})
console.log(hasUnderageStudents) //false

7.every()
作用:此方法与 some() 非常相似,除了检查至少一项以评估为真或假之外,它会检查以确保每一项都符合给定的条件。

const hasUnderageStudents = students.every((students) => {
  return students.age < 40
})
console.log(hasUnderageStudents)  //true
const hasUnderageStudents = students.every((students) => {
	return students.age < 18
})
console.log(hasUnderageStudents)  //false

8.reduce()
作用:对数组中的所有项目进行某种累积操作。例如我们计算学生的总分。

const totalScore = students.reduce((currentTotal, students) => {
  return students.score + currentTotal
}, 0)
console.log(totalScore) //406
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值