增
对原数组产生影响
- push()? ?接收任意量的参数,从数组尾部添加,返回值为数组最新长度。
let colors = ["orange"];// 创建一个数组
let count = colors.push("red", "green"); // 从数组尾部推入两项
console.log(count) // 2
console.log(colors) // red,green,orange
- unshift()? 从数组开头插入,返回数组最新长度
let colors = ["orange"]; // 创建一个数组
let count = colors.unshift("red", "green"); // 从数组开头推入两项
alert(count); // 2
console.log(colors); //['red', 'green', 'orange']
- splice()? 可传三个参数,分别是(开始位置、要删除元素的数量、插入的元素),返回删除的元素。ps:当作为增时,第二个参数要设为0。
let colors = ["red", "green", "blue"];
// 开始位置,0(若省略,则删除要插入的第一个元素),插入的元素
// 返回空数组
let removed = colors.splice(1, 0, "yellow", "orange")
console.log(colors) // red,yellow,orange,green,blue
console.log(removed) // []
对原数组不产生影响
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"]
删
对原数组产生影响
let colors = ["red", "green","orange"]
let item = colors.pop(); // 取得(删除)最后一项
console.log(item) // orange
console.log(colors) // red,green
let colors = ["red", "green","orange"]
let item = colors.shift(); // 取得第一项
console.log(item) // red
console.log(colors) // green,orange
- splice()??可传三个参数,分别是(开始位置、要删除元素的数量、插入的元素),返回删除的元素。ps:当作为删时,第三个参数不传。
let colors = ["red", "green", "blue"];
//开始位置,删除个数(可省,从开始位置之后全删除)。返回删除的数组
let removed = colors.splice(0,2); // 删除下标 0-1
console.log(colors); // green
console.log(removed); // red,green
对原数组不产生影响
let colors = ["red", "green", "blue", "yellow", "purple"];
//留下从 开始位置,结束位置(可省,默认到最后)的元素
let colors2 = colors.slice(1); //返回下边 1-末尾
let colors3 = colors.slice(1, 4); //返回下标1-3
console.log(colors) // red,green,blue,yellow,purple
concole.log(colors2); // green,blue,yellow,purple
concole.log(colors3); // green,blue,yellow
改--对原数组产生影响
splice()?可传三个参数,分别是(开始位置、要删除元素的数量、插入的元素),返回删除的元素。ps:当作为改时,三个参数都要传,第二个不为0。
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()? --- 返回要查找的元素的下标,否则返回-1
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.indexOf(4)
console.log(numbers.indexOf(4)); // 3 返回该元素所在位置,否则返回-1
- includes() ---?找到返回true,否则false
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.includes(4) // 3
console.log(numbers.includes(4)); //true 找到返回true,否则false
const people = [
{
name: "Matt",
age: 27
},
{
name: "Nicholas",
age: 29
}
];
people.find((element, index, array) => element.age < 28) // // {name: "Matt", age: 27}
|