js中数组Array常用方法

学习记录 - Array的常用方法

pop

  • 删除并返回最后一项
  • 改变原数组

push

  • 添加一项或多项到数组尾部
  • 返回新数组的长度
  • 改原数组

shift

  • 删除并返回第一项
  • 改原数组

unshift

  • 添加并返回第一项
  • 改变原数组

splice

  • 添加、替换、删除数组中的项
  • 第一个参数为开始添加、删除的下标
  • 第二个参数为删除多少项 0 为不删除
  • 第三个参数 可选 添加、替换的内容
  • 返回删除的项的值 以数组形式
  • 改变原数组
1
arr.splice(index,number,content)

sort

  • 无参数 将数组按首字符排序
  • 若参数为函数 可按函数要求排序
  • 改变原数组
1
2
3
4
5
6
arr.sort(function (a,b){    //从小到大排序
return a-b;
})
arr.sort(function (a,b){ //从大到小排序
return b-a;
})

reverse

  • 颠倒 将数组从右往左重新排序
  • 返回颠倒的数组
  • 不改原数组

slice

  • 截取 两个下标间的内容
  • 包含start 不包含end
  • 返回截取内容
  • 不会修改原数组
1
arr.slice(index,index)

toString

  • 将数组转换成字符串输出

join

  • 将数组的每项以参数连接
  • 不写默认 , 隔开

concat

  • 将b数组连接到a数组后面
1
a.concat(b)

some

  • 当数组中存在满足指定条件的项时
  • 返回 true
  • 否则 返回 false
1
2
3
arr.some(function(item,index,array){    //item:项,index:下标,array:数组
return item > 10; //有一个满足则返回true 否则false
})

every

  • 当数组中全部项都满足指定条件时
  • 返回 true
  • 否则 返回 false
    1
    2
    //item:项,index:下标,array:数组
    arr.every((item,index,array)=> item > 10) //全部满足则返回true 否则false

filter

  • 检测数组中的每一项
  • 返回 符合条件的项
  • 以数组形式
  • 否则 返回 空数组
  • 不改变原数组
    1
    2
    3
    let arr = [1,2,3,4,99];
    arr = arr.filter((item,index,array)=> item > 10);
    console.log(arr); // [99]

map

  • 对数组的每一项进行指定的操作
  • 返回 结果
  • 以数组的形式
  • 可遍历数组
    1
    2
    //遍历当前数组,生成新数组
    arr.map((item,idx,arr)=> item + 'hello world')

forEach

  • 对数组的每一项进行指定的操作
  • 可遍历数组
  • 返回 undefined
    1
    2
    3
    4
    //遍历数组
    arr.forEach( (item,idx,arr)=> {
    console.log(item,idx,arr)
    })

new Array()

  • 构建新数组
    1
    2
    let xxx = new Array();
    let xx = [];

遍历数组方法

  • for循环 / while 循环
  • for…in…循环
  • for…of….
  • ECMAScript5
    1
    2
    3
    4
    5
    6
    7
    8
    arr.forEach(function (item,idx,arr) { //遍历数组
    console.log(item,idx,arr)
    });

    arr.map(function (item,idx,arr) { //遍历当前数组,生成新数组
    console.log(item,idx,arr);
    return item + 'hello world'
    });

Array.from( )

  • 将类似数组的对象转为数组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    let arrayLike = {
    0: 'tom',
    1: '65',
    2: '男',
    3: ['jane','john','Mary'],
    'length': 4
    };
    let arr = Array.from(arrayLike);
    console.log(arr) // ['tom','65','男',['jane','john','Mary']]
  • 将一个类数组对象转换为一个真正的数组,必须具备以下条件:

    •  1、该类数组对象必须具有length属性,用于指定数组的长度。如果没有length属性,那么转换后的数组是一个空数组。
    •  2、该类数组对象的属性名必须为数值型或字符串型的数字
    •  ps: 该类数组对象的属性名可以加引号,也可以不加引号