数组常用方法总结

findIndex

常用情境:根据id找到数组的索引值

var arr = [1, 3, 6, 9]
var index = arr.findIndex((e) => {
    return e > 7
})
//简写
//var index = arr.findIndex((e) => e > 7)
console.log(index)

filter

常用情境:数组过滤,生成新数组

var arr = [1, 3, 8]
var arr2 = arr.filter((e) => {
    return e > 1
})
console.log(arr2)

map

常用情境:遍历数组,生成新数组(不改变原数组)

var users = [
  {name: "张含韵", "email": "zhang@email.com"},
  {name: "江一燕",  "email": "jiang@email.com"},
  {name: "李小璐",  "email": "li@email.com"}
];

var arr2 = users.map((e) => {
    return e.name
})
console.log(arr2) //["张含韵", "江一燕", "李小璐"]

splice

常用情境:删除数组中指定位置的元素(直接操作原数组)

var arr = ["didi", 2, 9]
arr.splice(0, 1)
console.log(arr)  //[2,9]
posted @ 2020-04-24 16:24  麦子同学  阅读(154)  评论(0编辑  收藏  举报