18个开发中常用的数组方法

46 阅读5分钟

开发中常用的数组方法

src=http___puui.qpic.cn_qqvideo_ori_0_d3323xijmph_1280_720_0&refer=http___puui.qpic.webp 面试的时候数组中的方法一直都是一个老生常谈并且重要的面试题,而咱们正常开发中使用到的方法,无非就是在数组中进行增加、删除、修改、查找的操作,但有些会问到哪些方法会一个新的数组?哪些方法会改变原数组?使用方法后返回的是数组的长度?会返回这也是我碰到过的,有点迷糊,总结一下。。

改变原数组的方法

1、新增

push() 方法将一个或多个元素添加到数组的末尾并返回数组的新长度

const sports = ['1', '2'];
const total = sports.push('3', '4');

console.log(sports); // ['1', '2', '3', '4']
console.log(total); // 4

unshift() 方法将一个或多个元素添加到数组的开头并返回数组的新长度

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

2、删除

pop() 删除最后一个元素并返回该元素

const num = ['1', '2', '3', '4'];

const res = num.pop();

console.log(num); // ['1', '2', '3' ]

console.log(res); // '4'

shift() 方法从数组中删除第一个元素返回该删除的元素,此方法更改数组的长度。

const num = ['1', '2', '3', '4'];

const res = num.shift();

console.log(num); // [ '2', '3','4' ]

console.log(res); // '1'

splice()删除替换现有元素或在适当位置splice()添加新元素来更改数组的内容。返回的是一个被删除元素的数组。

1、添加,即第二个参数为0时,表示插入
const myFish = ['0', '1', '3', '4'];
const removed = myFish.splice(2, 0, '2'); 
// myFish ['0', '1',,'2', '3', '4']
// removed [] 没有要删除的元素

2、删除,从索引为3开始,删除一个
const myFish = ['0', '1', '2', '3', '4'];
const removed = myFish.splice(3, 1);
// myFish ['0', '1',,'2', '4']
// removed ['3'] 没有要删除的元素

3、替换,就是先删除再插入
const months = ['0', '1', '2', '3'];
months.splice(2, 1, '1');

console.log(months); ["0", "1", "1", "3"]

返回的依然是被删除的元素数组['2']

3、排序

sort() 方法对数组的元素进行就地排序,并返回对同一个数组的引用,现在已排序。

原理是:将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);// Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);// Array [1, 100000, 21, 30, 4]

shift() 方法从数组中删除第一个元素返回该删除的元素,此方法更改数组的长度。

const num = ['1', '2', '3', '4'];

const res = num.shift();

console.log(num); // [ '2', '3','4' ]

console.log(res); // '1'

不改变原数组

1、entries

英文翻译为条目,字母意思就是返回一个条目。。。。

entries() 方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对

const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}
console.log(arrayEntries); //一个新的Array Iterator对象 Array Iterator {}
// [0, 'a']
// [1, 'b']
// [2, 'c']

2、concat(合并)

concat() 方法用于合并两个或多个数组。返回一个新数组,原数组不变

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);
console.log(numbers);// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]

3、forEach

方法对每个数组元素执行一次提供的函数。返回值是undefined

const array1 = ['a', 'b', 'c'];

let a= array1.forEach((element,index,array) =>{
    console.log(element,index,array)
    > "a" 0 Array ["a", "b", "c"] 
    > "b" 1 Array ["a", "b", "c"] 
    > "c" 2 Array ["a", "b", "c"]
});
console.log(a)
undefined

可见第一个参数为数组元素,第二个为数组索引,第三个为该数组

4、展平数组 flat

flat() 方法返回一个新数组,其中所有子数组元素递归连接到指定深度

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

综上:

参数默认为1,也就是说默认只展平数组中的第一层

参数为2时,也就是展平数组中的2层

参数为Infinity,展开全部

也可以使用forEach

const flatten = (arr) => {
  const result = [];
  arr.forEach((item) => {
    if (Array.isArray(item)) {
      result.push(...flatten(item));
    } else {
      result.push(item);
    }
  });
  return result;
}
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]];
console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

5、filter(过滤)

filter() 方法创建给定数组的一部分的浅表副本,过滤到仅通过给定函数实现的测试的给定数组中的元素。返回一个新数组使用方法和forEach相似

const words = ['1', '2', '3', '4', '5', '6'];

const result = words.filter(word => word > 4);

console.log(result); //56
console.log(words);//123456

6、every和some

every()方法测试数组中的所有元素是否通过提供的函数实现的测试。它返回一个布尔值。 意思就是:是否都满足某个条件

比如:判断array1中的元素是否都是小于40

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 20, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

some()方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。如果在数组中找到所提供函数为其返回 true 的元素,则返回 true;否则返回false。它不会修改数组,意思就是:是否存在满足某个条件

const array = [1, 1, 2, 9, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

7、includes(包含)

includes() 方法确定数组是否包含某个值,返回true或 false

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));

8、slice(截取)

slice()方法将截取数组的一部分返回一个新的数组,选自【start,end)(不包括end)

const animals = ['0', '1', '2', '3', '4'];

console.log(animals.slice(2));
// expected output: Array ["2", "3", "4"]

console.log(animals.slice(2, 4));
// expected output: Array ["2", "3"]

console.log(animals.slice(1, 5));
// expected output: Array ["1", "2", "3", "4"]

console.log(animals.slice(-2));
// expected output: Array ["3", "4"]

console.log(animals.slice(2, -1));
// expected output: Array ["2", "3"]

console.log(animals.slice());
// expected output: Array['0', '1', '2', '3', '4'];

9、map

map() 创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果 用法和forEach差不多


const kvArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];

const reformattedArray = kvArray.map(({ key, value}) => ({ [key]: value }));

// reformattedArray is now
        [
           {1: 10},
           {2: 20}, 
           {3: 30}
        ],

// kvArray is still:
//   [
//      {key: 1, value: 10},
//      {key: 2, value: 20},
//      {key: 3, value: 30}
//   ]

在正常开发过程中主要还是用的push、map、filter等,才疏学浅只能到这。。。。