乐趣区

关于javascript:javascript-数组的常用方法有哪些

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

数组的基本操作能够演绎为 增、删、改、查,须要注意的是哪些办法对原数组产生影响,哪些办法不会。

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

以下前三种是对原数组产生影响的削减办法,第四种则不会对原数产生影响

  • 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}

排序办法

退出移动版