整理了一下ES6中数组常见的操作方法,包含:forEach、map、filter、some、every、reduce、findIndex、find、slice、splice、push、unshift
。
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
users.forEach(e => {
console.log(e)
})
users
中,我们希望返回一个新的数组,里面只包含每个人的名称 const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
const newUsers = users.map(e => {
return e.name
})
console.log(newUsers)
users
中,我们希望返回年龄大于等于18的用户 const users = [
{
id: 1,
age:15,
name: "王大锤"
},
{
id: 2,
age:18,
name: "二狗子"
},
{
id: 3,
age:23,
name: "路飞"
}
]
const newUsers = users.filter(e => {
return e.age >= 18
})
console.log(newUsers)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
const b = users.some(e => {
return e.age > 22
})
console.log(b)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
const b = users.every(e => {
return e.age >= 18
})
console.log(b)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
// (ageSum, e) 中两个参数分别为:累计器和当前值
// reduce函数的第二个参数0,表示初始值
const ageSum = users.reduce((ageSum, e) => {
return ageSum += e.age
}, 0)
console.log('平均年龄为:', (ageSum / users.length).toFixed(2))
-1
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
const index = users.findIndex(e => {
return e.name === "二狗子"
})
console.log(index)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
const user = users.find(e => {
return e.age > 16
})
console.log(user)
不会影响原数组
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
// 从1开始,到3结束,不包含3
const newUsers = users.slice(1,3)
console.log(newUsers)
会影响原数组
,常用于按下标删除数组中的值 const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
// 下标开始位置,要删除的数量
users.splice(1,2)
console.log(users)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
users.push({id: 4, age: 25, name: "柯南"})
console.log(users)
const users = [
{
id: 1,
age: 15,
name: "王大锤"
},
{
id: 2,
age: 18,
name: "二狗子"
},
{
id: 3,
age: 23,
name: "路飞"
}
]
users.unshift({id: 4, age: 25, name: "柯南"})
console.log(users)
const arr = [1,2,1,2,2,3,4,5]
// 转Set
const newArr= Array.from(new Set(arr))
console.log(newArr);
const arr = [1,2,1,2,2,3,4,5]
const newArr = arr.filter((item, index) => {
// 判断当前值的下标值是否在前面出现过,若前面有相同值,则arr.indexOf(item)必然小于index
return arr.indexOf(item) === index
})
console.log(newArr);