增删改只有concat不能改变原数组,增删改查之外只有sort和reverse以及复杂数组时的map方法会改变
添加数组元素
push(在数组末尾添加数组元素)
var arr1 = [1,2,3,4];
var b = [5,6,7,8];
arr1.push(b);
b.push(9,10,11);//可同时push多个值
console.log(b);//[1,2,3,4,Array(4)]
console.log(b);//[5,6,7,8,9,10,11]
unshift(在数组开头添加数组元素)
var arr = [1,2,3];
var b = [4,5,6];
arr.unshift(...b);
console.log(arr);//[4,5,6,1,2,3]
concat
concat不会改变原数组
var arr = [1,2,3];
var c = [5,6,7]
var b = arr.concat(c);
console.log(arr);//[1,2,3]
console.log(b);//[1,2,3,5,6,7]
splice
在某个数组元素的前面添加
<script>
var arr = [1,2,3,4]
var b = [7,8,9]
arr.splice(2,0,...b)
console.log(arr)//[1,2,7,8,9,3,4]
</script>
数组展开
“…”加数组可将数组展开
var arr1 = [1,2,3,4];
var b = [5,6,7,8];
arr.push(...b);
console.log(arr);//[1,2,3,4,5,6,7,8]
删除数组元素
pop(在数组末尾删除数组元素)
shift(在数组开头删除数组元素)
var arr = [1,2,3,4];
arr.pop();
arr.shift();
console.log(arr)//[2,3]
定点删除splice(index,howmany)
index 从哪个下标开始 howmany 删除多少个
var arr = [1,2,3,4,5];
arr.splice(3,1);
console.log(arr); //[1,2,3,5];
修改数组元素splice(index,howmany,value)
index 从哪个下标开始 howmany 删除多少个 value 插入的值(可以是多个值)
var arr = [1,2,3,4,5];
var b = [1,2,3,4,5];
arr.splice(2,1,7);
b.splice(2,3,7,8,9);
console.log(arr); //[1,2,7,4,5]
console.log(b); //[1,2,7,8,9]
查询数组元素
indexOf —查询数组某个值的下标
只会查询到元素出现第一次的下标
var arr = [1,4,3,4];
console.log(arr.indexOf(4));//1
findIndex
只会查询到元素出现第一次的下标
var arr = [1,2,3,2];
var index = arr.findIndex(item=>{
return item == 2;
})
console.log(index);//1
find
找到第一个符合条件的值并返回
<script>
var a = [1,2,3,4]
var res = a.find(item=>{
return item == 3
})
console.log(res) //3
console.log(a)
</script>
截取数组片断
slice(startIndex,endIndex) 不包含endIndex
slice(startIndex) 截取从startIndex开始到后面所有的值
var arr = [1,2,3,4];
console.log(arr.slice(1,3))//[2,3]
console.log(arr.slice(1))//[2,3,4]
例子
<script>
var arr = [1,2,3,4,5,6,7,8,9]
//[[1,2,3],[4,5,6],[7,8,9]]
var sum =[];
for(var i=0;i<arr.length;i=i+3){
var item = arr.slice(i,i+3);
sum.push(item);
}
console.log(sum)
</script>