增删改只有concat不能改变原数组,增删改查之外只有sort和reverse以及复杂数组时的map方法会改变

添加数组元素

push(在数组末尾添加数组元素)

  1. var arr1 = [1,2,3,4];
  2. var b = [5,6,7,8];
  3. arr1.push(b);
  4. b.push(9,10,11);//可同时push多个值
  5. console.log(b);//[1,2,3,4,Array(4)]
  6. console.log(b);//[5,6,7,8,9,10,11]

unshift(在数组开头添加数组元素)

  1. var arr = [1,2,3];
  2. var b = [4,5,6];
  3. arr.unshift(...b);
  4. console.log(arr);//[4,5,6,1,2,3]

concat

concat不会改变原数组

  1. var arr = [1,2,3];
  2. var c = [5,6,7]
  3. var b = arr.concat(c);
  4. console.log(arr);//[1,2,3]
  5. console.log(b);//[1,2,3,5,6,7]

splice

在某个数组元素的前面添加

  1. <script>
  2. var arr = [1,2,3,4]
  3. var b = [7,8,9]
  4. arr.splice(2,0,...b)
  5. console.log(arr)//[1,2,7,8,9,3,4]
  6. </script>

数组展开

“…”加数组可将数组展开

  1. var arr1 = [1,2,3,4];
  2. var b = [5,6,7,8];
  3. arr.push(...b);
  4. console.log(arr);//[1,2,3,4,5,6,7,8]

删除数组元素

pop(在数组末尾删除数组元素)

shift(在数组开头删除数组元素)

  1. var arr = [1,2,3,4];
  2. arr.pop();
  3. arr.shift();
  4. console.log(arr)//[2,3]

定点删除splice(index,howmany)

index 从哪个下标开始 howmany 删除多少个

  1. var arr = [1,2,3,4,5];
  2. arr.splice(3,1);
  3. console.log(arr); //[1,2,3,5];

修改数组元素splice(index,howmany,value)

index 从哪个下标开始 howmany 删除多少个 value 插入的值(可以是多个值)

  1. var arr = [1,2,3,4,5];
  2. var b = [1,2,3,4,5];
  3. arr.splice(2,1,7);
  4. b.splice(2,3,7,8,9);
  5. console.log(arr); //[1,2,7,4,5]
  6. console.log(b); //[1,2,7,8,9]

查询数组元素

indexOf —查询数组某个值的下标

只会查询到元素出现第一次的下标

  1. var arr = [1,4,3,4];
  2. console.log(arr.indexOf(4));//1

findIndex

只会查询到元素出现第一次的下标

  1. var arr = [1,2,3,2];
  2. var index = arr.findIndex(item=>{
  3. return item == 2;
  4. })
  5. console.log(index);//1

find

找到第一个符合条件的值并返回

  1. <script>
  2. var a = [1,2,3,4]
  3. var res = a.find(item=>{
  4. return item == 3
  5. })
  6. console.log(res) //3
  7. console.log(a)
  8. </script>

截取数组片断

slice(startIndex,endIndex) 不包含endIndex
slice(startIndex) 截取从startIndex开始到后面所有的值

  1. var arr = [1,2,3,4];
  2. console.log(arr.slice(1,3))//[2,3]
  3. console.log(arr.slice(1))//[2,3,4]

例子

  1. <script>
  2. var arr = [1,2,3,4,5,6,7,8,9]
  3. //[[1,2,3],[4,5,6],[7,8,9]]
  4. var sum =[];
  5. for(var i=0;i<arr.length;i=i+3){
  6. var item = arr.slice(i,i+3);
  7. sum.push(item);
  8. }
  9. console.log(sum)
  10. </script>