基础面试题 3 - 常用数组方法(增删改查)

71 阅读2分钟

以下根据分组更好记忆

  • join / split
  • push/pop/shift/unshift
  • reverse/sort
  • contact/splice/slice

字符串与数组之间的转化:join / split

let arr = [1, 2, 3];
let str = arr.join("#")
console.log(arr)
console.log(str);

let arr2 = str.split("#")
console.log(arr2)
  • join:arr.join(字符) 不改变原数组,根据传入的字符将数组拼接成字符串并返回
  • split:str.split(字符) 不改变原字符串,将数组对象根据传入的字符拆分成数组并返回

数组首尾元素的增删:push/pop/shift/unshift

let arrTwo1 = [0, 1, 2];

let res = arrTwo1.push(6);
console.log('res', res);
console.log('arrTwo1 push', arrTwo1);

let res1 = arrTwo1.pop();
console.log('res1', res1);
console.log('arrTwo1 pop', arrTwo1);

let res2 = arrTwo1.unshift(8);
console.log('res2', res2);
console.log('arrTwo1 unshift', arrTwo1);

let res3 = arrTwo1.shift();
console.log('res3', res3);
console.log('arrTwo1 shiift', arrTwo1);
  • push: arr.push(新增元素),在数组尾部增加传入元素,改变原数组,返回新数组长度
  • pop: arr.pop(),数组尾部删除一个元素,改变原数组,返回删除元素
  • unshift: arr.unshift(新增元素),在数组头部新增传入元arr.unshift(新增元素)素,改变原数组,返回新数组长度
  • shift: arr.shift(),删除数组首arr.shift()部一个元素,改变原数组,返回删除元素

数组的排序:reverse/sort

let arrThree = [3, 4, 5];

let res = arrThree.reverse();
console.log('res', res);
console.log('arrThree', arrThree);

let res1 = arrThree.sort((a, b) => a - b);
console.log('res1', res1);
console.log('arrThree sort', arrThree);
  • reverse:arr.reverse(),反转数组,改变原数组,返回新数组
  • sort: arr.sort((a,b)=>a-b),将数组排序,默认传参 a<b,根据返回值a-b<0 将数组从小到大排列,反之从大到小排列,改变原数组,返回新数组

其他方法:splice/slice/contact

let arr = [1, 3, 5, 7, 9];
// splice 的三种使用
let res = arr.splice(3);
console.log('res', res);
console.log('arr', arr);

let res1 = arr.splice(2, 1);
console.log('res1', res1);
console.log('arr1', arr);

let res2 = arr.splice(0, 0, 2, 4);
console.log('res2', res2);
console.log('arr2', arr);

let arr2 = [2, 4, 6, 8];
// slice 的三种使用
let res3 = arr2.slice();   // 复制原数组
console.log('res3', res3); // res3 [ 2, 4, 6, 8 ]
console.log('arr2', arr2); // arr2 [ 2, 4, 6, 8 ]

let res4 = arr2.slice(3);
console.log('res4', res4); // res4 [ 8 ]
console.log('arr2', arr2); // 不改变原数组 arr2 [ 2, 4, 6, 8 ]

let res5 = arr2.slice(1, 2);
console.log('res5', res5); // “含头不含尾” res5 [ 4 ]
console.log('arr2', arr2); // arr2 [ 2, 4, 6, 8 ]

// concat 使用
let arr3 = [1, 2],
  arr4 = [9, 8];
let res6 = arr3.concat(arr4);
console.log('res6', res6);
console.log('arr4', arr4);

  • splice: array.splice(start[, deleteCount[, item1, item2, ...]]),第2、3 个参数可选传递,可实现部分及整体删除、替换、插入元素到数组,会改变原数组,返回删除元素组成的新数组
  • slice:array.slice([start[end]]),通过指定起始索引start和结束索引end,可以提取原数组或字符串中从startend(不包括end)之间的元素(含头不含尾),不修改原数组或字符串,返回新数组或字符串
  • concat: arr1.concat(arr2,arr3...),concat可实现多个数组或者字符串的拼接,不修改原数组及字符串,返回新的数组及字符串