一、添加元素
这里面我们介绍三个方法
array.push(item1,item2……itemN);//将一个或多个元素加入数组,返回新数组的长度
array.unshift(item1,item2……itemN);//将一个或多个元素加入到数组的开始位置,原有元素位置自动后移,返回 新数组的长度
array.splice(start,delCount,item1,item2……itemN);//从start的位置开始向后删除delCount个元素,然后从start的位置开始插入一个或多个新元素
二、查找元素
这里面介绍两个方法:
indexOf() 方法可返回数组中某个指定的元素第一次出现的位置,没有返回-1.
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值
//测试数组
var test = [1, 2, 3, 4, 3, 4, 5];
//=====================查找
//查找下标为3的第一个元素
var index = test.indexOf(3);
console.log(index);
//=====================查找
var arr = test.find((val) => {
return val > 3;
});
console.log('arr', arr);//arr 4
三、删除元素
这里面我们也介绍两个方法
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。注意不会改变原数组。
splice() 方法用于添加或删除数组中的元素。
举例,我们要删除数组中的某一个元素,例如我们要删除数组中的3元素。
可以发现使用filter可以删除满足条件的所有元素,而使用splice只能通过索引。
//测试数组
var test = [1, 2, 3, 4, 3, 4, 5];
//查找下标为3的第一个元素
var index = test.indexOf(3);
//=====================筛选元素
var arr2 = test.filter((val) =>{
return val != 3;
});
console.log('arr2', arr2); //[ 1, 2, 4, 4, 5 ]
//=====================删除第一个3
test.splice(index, 1);
console.log("----------", test); //[ 1, 2, 4, 3, 4, 5 ]
这里在重点介绍一下splice方法,可以对数组删除、替换。
test2.splice(1, 1);//结果test2=['a','c','d'](下标1开始,删除1个)
var test2 = ['a', 'b', 'c', 'd'];
//spice增加:
test2.splice(1, 0, 'str'); //结果arr=['a','str','b','c','d']
console.log('test2', test2);
//spice替换:
test2.splice(1, 1, 'str'); //结果arr=['a','str','c','d']
//spice替换2:
test2.splice(1,2,'str'); //结果arr=['a','str','d'](就是说:下标1开始2个换成1个“str”)
//spice删除多个:
test2.splice(1,2); //结果arr=['a','d']