欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
数组的常用方法有下面几种
 
方法 释义
 
push()
 
push()⽅法可以接收任意数量的参数,并将它们添加到数组末尾,返回数组的最新⻓度
 
unshift()
 
unshift() 在数组开头添加任意多个值,然后返回新的数组⻓度
 
splice()
 
传⼊三个参数,分别是开始位置、 0 (要删除的元素数量)、插⼊的元素,返回空数组
 
concat()
 
⾸先会创建⼀个当前数组的副本,然后再把它的参数添加到副本末尾,最后返回这个新构建的数组,不会影响原始数组
 
pop()
 
pop() ⽅法⽤于删除数组的最后⼀项,同时减少数组的 length 值,返回被删除的项
 
shift()
 
shift() ⽅法⽤于删除数组的第⼀项,同时减少数组的 length 值,返回被删除的项
 
splice()
 
传⼊两个参数,分别是开始位置,删除元素的数量,返回包含删除元素的数组
 
slice()
 
slice() ⽤于创建⼀个包含原有数组中⼀个或多个元素的新数组,不会影响原始数组
 
indexOf()
 
返回要查找的元素在数组中的位置,如果没找到则返回 -1
 
includes()
 
返回要查找的元素在数组中的位置,找到返回 true ,否则 false
 
find()
 
返回第⼀个匹配的元素
 
数组的两个排序方法
 
reverse()    反转数组
 
let values = [1, 2, 3, 4, 5];
 
values.reverse();
 
alert(values); // 5,4,3,2,1
 
sort()
 
sort() ⽅法接受⼀个⽐较函数,⽤于判断哪个值应该排在前⾯
 
数组方法的基本操作   
 
 
数组基本操作可以归纳为 增、删、改、查,需要留意的是哪些⽅法会对原数组产⽣影响,哪些⽅法不会
 
push()
 
let colors = []; // 创建⼀个数组
 
let count = colors.push("red", "green"); // 推⼊两项
 
console.log(count) // 2
 
unshift()
 
let colors = new Array(); // 创建⼀个数组
 
let count = colors.unshift("red", "green"); // 从数组开头推⼊两项
 
alert(count); // 2
 
splice()
 
let colors = ["red", "green", "blue"];
 
let removed = colors.splice(1, 0, "yellow", "orange")
 
console.log(colors) // red,yellow,orange,green,blue
 
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()
 
let colors = ["red", "green"]
 
let item = colors.pop(); // 取得最后⼀项
 
console.log(item) // green
 
console.log(colors.length) // 1
 
shift()
 
let colors = ["red", "green"]
 
let item = colors.shift(); // 取得第⼀项
 
console.log(item) // red
 
console.log(colors.length) // 1
 
splice()
 
let colors = ["red", "green", "blue"];
 
let removed = colors.splice(0,1); // 删除第⼀项
 
console.log(colors); // green,blue
 
console.log(removed); // red,只有⼀个元素的数组
 
1234
 
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
 
concole.log(colors2); // green,blue,yellow,purple
 
concole.log(colors3); // green,blue,yellow
 
 
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()
 
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
 
numbers.indexOf(4) // 3
 
includes()
 
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
 
numbers.includes(4) // true
 
find()
 
const people = [
 
 {
 
 name: "Matt",
 
 age: 27
 
 },
 
 {
 
 name: "Nicholas",
 
 age: 29
 
 }
 
];
 
people.find((element, index, array) => element.age < 28) // // {name:
 
"Matt", age: 27}
 
以上就是对数组方法的一些总结

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64391.shtml