数组的常用的方法总结

122 阅读4分钟

1 arr.push()

从后面添加元素,返回值为添加完后的数组的长度

let arr = [1,2,3,4,5]
console.log(arr.push(5))   // 6
console.log(arr) // [1,2,3,4,5,5]

2 arr.pop()

从后面删除元素,只能是一个,返回值是删除的元素

let arr = [1,2,3,4,5]
console.log(arr.pop())     // 5
console.log(arr)  //[1,2,3,4]

3 arr.shift()

从前面删除元素,只能删除一个 返回值是删除的元素

let arr = [1,2,3,4,5]
console.log(arr.shift())  // 1
console.log(arr)   // [2,3,4,5]

4 arr.unshift()

从前面添加元素, 返回值是添加完后的数组的长度

let arr = [1,2,3,4,5]
console.log(arr.unshift(2))    // 6
console.log(arr)  //[2,1,2,3,4,5]

5.map

遍历数组,有返回值,并且不会影响原来的数组

const arr=[
    {name:'foo',age:18,gender:'0'},
    {name:'foo',age:18,gender:'0'},
    {name:'bar',age:22,gender:'0'},
    {name:'jack',age:19,gender:'1'},
]
const arrTemp=arr.map((res)=>{
    return {
        checkName:res.name,
        checkAge:res.age
    }
})
console.log(arrTemp);

6.forEach

遍历数组,无返回值,并且会影响原来的数组

const arr=[    {name:'foo',age:18,gender:'0'},    {name:'foo',age:18,gender:'0'},    {name:'bar',age:22,gender:'0'},    {name:'jack',age:19,gender:'1'},]
let arrTemp=[]
arr.forEach((res)=>{
    if(res.age==18){
        arrTemp.push(res)
    }
})
console.log(arrTemp);
//
[    {name:'foo',age:18,gender:'0'},    {name:'foo',age:18,gender:'0'},]

7.find

此方法接受一个函数,查找第一个符合条件的数组元素,当条件成立为true时,返回该元素。如果没有符合条件的元素,返回值为undefined。

const arr=[
    {name:'foo',age:18,gender:'0'},
    {name:'foo',age:18,gender:'0'},
    {name:'bar',age:22,gender:'0'},
    {name:'jack',age:19,gender:'1'},
]
const arrtemp=arr.find((res)=>{
      return res.name==='foo'
    })
console.log(arrtemp); //{name: 'foo', age: 18, gender: '0'}

8.filter

过滤数组,返回一个满足要求的数组 还有去除null,undefind的功能

const arr=[
    {name:'foo',age:18,gender:'0'},
    {name:'foo',age:18,gender:'0'},
    {name:'bar',age:20,gender:'0'},
    {name:'jack',age:19,gender:'1'},
]
const arrTemp=arr.filter((res)=>{
    return res.age>18
})
console.log(arrTemp);
--------------------------
const arr=[1,null,undefined,'foo',{a:1}]
const arrTemp=arr.filter((res)=>{
    return res
})
console.log(arrTemp);//[1,'foo',{a:1}]

9.every

依据判断条件,数组的元素是否全满足,若满足则返回ture

const arr=[
    {name:'foo',age:18,gender:'0'},
    {name:'foo',age:18,gender:'0'},
    {name:'bar',age:20,gender:'0'},
    {name:'jack',age:19,gender:'1'},
]
const arrTemp=arr.every((res)=>{
    return res.age>18
})
console.log(arrTemp);//false

10.some

依据判断条件,数组的元素是否有一个满足,若有一个满足则返回ture
const arr=[
    {name:'foo',age:18,gender:'0'},
    {name:'foo',age:18,gender:'0'},
    {name:'bar',age:20,gender:'0'},
    {name:'jack',age:19,gender:'1'},
]
const arrTemp=arr.some((res)=>{
    return res.age>18
})
console.log(arrTemp);//true

11.reduce

reduce方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

接受2个参数,第一个参数是一个回调函数,此函数接受4个参数,第二个参数是一个初始值

callback    
    accumulator --累计器累计回调的返回值;
    currentValue  --数组中正在处理的元素。
    index  --数组本身在处理的当前元素的索引 (可选)
    array  --数组本身(可选)
initialValue --作为第一次调用 callback函数时的第一个参数的值
​
​
arr.reduce(
    (accumulator, currentValue, currentIndex, array) => {}, 
    initialValue
)
普通数组求和
const sum = [0, 1, 2, 34].reduce( (accumulator, currentValue) =>{
    return accumulator + currentValue;
});
console.log(sum);  //10
​
解析:
因为没有初始值,所以accumulator从第一项开始(0),currentValue从第二项开始 (1),accumulator每次都是从上一次返回的值,所以叫做累加器
callbackaccumulatorcurrentValuereturn value
第一次011
第二次123
第三次336
第四次6410
对象数组求和
const initialValue = 0;
const sum = [{ x: 1 }, { x: 2 }, { x: 3 },{x:4}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    , initialValue
);
​
console.log(sum) // 10
二维数字转一维数组
const arr=[[0, 1], [2, 3], [4, 5]]
​
const arrTemp=arr.reduce((accumulator,currentValue)=>{
    return [...accumulator,...currentValue]
})
console.log(arrTemp);  //[0, 1, 2, 3, 4, 5]
计算数组中每个元素出现的次数
const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
const countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
按属性对object分类
const people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];
​
function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
​
var groupedPeople = groupBy(people, 'age');
​
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }
​
使用扩展运算符和initialValue绑定包含在对象数组中的数组
​
const friends = [
    {
      name: 'Anna',
      books: ['Bible', 'Harry Potter'],
      age: 21
    }, 
    {
      name: 'Bob',
      books: ['War and peace', 'Romeo and Juliet'],
      age: 26
    },
    {
      name: 'Alice',
      books: ['The Lord of the Rings', 'The Shining'],
      age: 18
    }
];
​
​
const allbooks = friends.reduce(function(prev, curr) {
  return [...prev, ...curr.books];
}, ['Alphabet']);
​
// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]
​

\