博客列表 >数组常用api

数组常用api

木子木杉
木子木杉原创
2022年01月08日 11:11:14581浏览

数组常用api

字面量

  1. let arr = [1, 2, "a", "b", true, false, { x: 1, y: 2 }, [1, 2], function () {}];
  2. console.log(arr);

…rest

  1. arr = [4, 5, 6];
  2. let arr1 = [...arr];
  3. console.log(arr1);

Array.of

  1. let a = [1, 2, 3, 4, 5, 6, true, function () {}];
  2. arr = Array.of(...a);
  3. console.log(arr);

Array.from

  1. const likeArr = {
  2. 0: "家",
  3. 1: "公司",
  4. 2: "学校",
  5. length: 3,
  6. };
  7. console.log(likeArr);
  8. console.log(Array.from(likeArr));

尾部增删,push从左到右进入,pop从右到左删除

  1. let arr = [];
  2. console.log(arr.push(1));
  3. console.log(arr.push(2, 3));
  4. console.log(arr);
  5. console.log(arr.pop());
  6. console.log(arr.pop());
  7. console.log(arr.pop());

头部增删,unshift从右到左增加,shift从左到右删除

  1. console.log(arr.unshift(1));
  2. console.log(arr.unshift(3, 2));
  3. console.log(arr);
  4. console.log(arr.shift());
  5. console.log(arr.shift());
  6. console.log(arr.shift());
  7. console.log(arr);

delete:删除指定的

  1. arr = [1, 2, 3, 4, 5, 6, 7];
  2. delete arr[4];
  3. console.log(arr);
  4. arr.length = 4;
  5. console.log(arr);

forEach((item,index,arr)=>{…})每个元素逐个调用,没有返回值

  1. let arr = [4, 5, 6, 7];
  2. arr.forEach((item, index, arr) => console.log(item, index, arr));

map;参数与功能与forEach一样,只是有返回值

  1. res = arr.map(item => item * 2);
  2. console.log(res);

every,some 断言函数,返回true,false
every:数组成员全部满足条件,返回true,否则false

  1. console.log(arr.every(item => item >= 0));
  2. console.log(arr.every(item => item >= 5));

some:数组成员有一个满足条件,返回true,否则false

  1. console.log(arr.some(item => item >= 6));
  2. console.log(arr.some(item => item >= 8));

filter:返回数组满足条件的元素,组成新数组,find返回新数组的第一个元素,findIndex返回新数组的第一个索引

  1. console.log(arr.filter(item => item >= 5));
  2. console.log(arr.find(item => item >= 6));
  3. console.log(arr.findIndex(item => item >= 6));

reduce 归并

  1. res = arr.reduce(function (acc, cur, index, arr) {
  2. return acc + cur;
  3. }, 5);
  4. console.log(res);

sort 排序

  1. let arr = [20, 30, 14, 53];
  2. console.log(arr.sort());
  3. console.log(arr.sort((a, b) => a - b));//升序
  4. console.log(arr.sort((a, b) => b - a));//降序

join:array->String

  1. arr = ["a", "b", "c"];
  2. console.log(arr.join());
  3. console.log(arr.join("-"));

splice:删除,新增,替换

  1. console.log(arr);
  2. console.log(arr.slice(5, 2));
  3. console.log(arr);
  4. console.log(arr.splice(1, 2, "a", "b"));
  5. console.log(arr);
  6. console.log(arr.slice(2, 0, "red", "green"));
  7. console.log(arr);
  8. let data = ["red", "green", "blue"];
  9. console.log(arr.splice(2, 0, ...data));
  10. console.log(arr);
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议