likes
comments
collection
share

javascript 数组的常用方法有哪些

作者站长头像
站长
· 阅读数 285

数组常见的方法可分为:操作方法,排序方法,转换方法,迭代方法

数组的基本操作可以归纳为 增、删、改、查,需要留意的是哪些方法对原数组产生影响,哪些方法不会。

操作方法(增、删、改、查)

以下前三种是对原数组产生影响的增添方法,第四种则不会对原数产生影响

  • push()
  • unshift()
  • splice()
  • concat()

push()方法接收任意数量的参数,并将他们添加到数组末尾,返回数组的最新长度

let colors = []; //创建一个数组
let count = colors.push("brown","purple"); //从数组末尾推入两项
console.log(count) //2

unshift()在数组开头添加任意多个值,然后返回新的数组长度

let colors = new Array(); // 创建一个数组
let count = colors.unshift("orange","yellow");//从数组开头推入两项
console.log(count) //2

splice()传入三个参数,分别是开始位置、0(要删除的元素数量)、插入的元素,返回空数组

let colors = ["blue","green","pink"];
let removed = colors.splice(1,0,"yellow","orange"); 
console.log(colors); // blue,yellow,orange,green,pink
console.log(removed);//[]

concat(),首先会创建一个当前数组的副本,然后再把它的参数添加到副本末尾,然后返回这个新构建的数组,不会影响原始数组

let colors = ["red","green","blue"];
let colors2 = colors.concat("yellow",["black","brown"]);
console.log(colors); // ["red","green","blue"]
console.log(colors2); //["red","green","blue","yellow","black","brown"]

以下前三种都会影响原数组,最后一项不影响原数组

  • pop()
  • shift()
  • splice()
  • slice()

pop()方法用于删除数组的最后一项,同时减少数组的length值,返回被删除的项

let colors = ["red","green"];
let item = colors.pop();//取得最后一项 
console.log(item) ;//green
console.log(colors);//1

shift()方法用于删除元素的第一项,同时减少数组的length值,返回被删除的项

let colors = ["red","green"];
let item = colors.shift();//取得第一项
console.log(colors.length)//1
console.log(item);//red

splice()方法传入两个参数,分别是开始位置,删除元素的数量,返回包涵删除元素的数组

let colors = ["red","green","blue"];
let removed = colors.splice(0,1);//删除第一项
console.log(colors); // green,blue
console.log(removed);//red,只有一个元素的数组

slice()用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组

let colors = ["red","green","blue","yellow","purple"];
let colors2 = colors.slice(1);
let colors3 = colors.slice(1,4);
console.log(colors);//red,green,blue,yellow,purple
console.log(colors2);green,blue,yellow,purple
console.log(colors3);green,blue,yellow

修改原来数组的内容,常用splice()splice()传入三个参数,分别是开始位置,要删除元素的数量,要插入的任意多个元素,返回删除元素的数组,对原数组产生影响

let colors = ["red","green","blue"];
let removed = colors.splice(1,1,"red","purple");
console.log(colors);//red,red,purple,blue
console.log(removed);//green 只有一个元素的数组

查找元素,返回元素坐标或者原素值

  • indexof()
  • inclueds()
  • find()

indexof()返回要查找的元素在数组中的位置,如果没找到则返回-1

let numbers = [1,2,3,4,5,4,3,2,1];
console.log(numbers.indexof(4)); //3

inclueds()返回要查找元素在数组中的位置,找到返回true,否则返回false

let numbers = [1,2,3,4,5,4,3,2,1];
console.log(numbers.inclueds(4)); //true

find()返回第一个匹配的元素

const people = [
    {name:"Jane",age:18},
    {name:"Matt",age:20}
]
let result = people.find((element,index,array)=>element.age<19)
console.log(result)//{name:"Jane",age:18}

排序方法