JS数组常用方法,看这篇就够了

171 阅读5分钟

前言

大部分时候后台返回的数据并不是前端想要的,这就需要我们对数据进行加工处理,这其中数组类型的数据最多,JS提供了很多数组方法,用好它们定能事半功倍。对于数组方法我们需要关注3个点:1.传入的参数 2.返回值 3.是否改变原数组

常用方法

pop

从数组中删除最后一个元素,返回删除的元素的值,改变原数组

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop()); // "tomato"
console.log(plants); // ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();
console.log(plants); // ["broccoli", "cauliflower", "cabbage"]

push

将一个或多个元素添加到数组的末尾,返回该数组的新长度,改变原数组

const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 4
console.log(animals); // ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals); // ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

shift

删除数组第一个元素,返回该元素的值,改变原数组

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); // [2, 3]
console.log(firstElement); // 1

unshift

将一个或者多个元素添加到数组的开头,返回该数组的新长度,改变原数组

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 5
console.log(array1); // [4, 5, 1, 2, 3]

reverse

颠倒数组元素位置,返回该数组,改变原数组

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1); // "array1:" ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed); // "reversed:" ["three", "two", "one"]
console.log('array1:', array1); // "array1:"["three", "two", "one"]

sort

对数组元素进行排序,并返回数组,默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

也可以写成:
var numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]

filter

从数组中过滤出一个新数组,参数接收一个函数,返回过滤后的数组,不改变原数组

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); // ["exuberant", "destruction", "present"]

find

从数组找出满足条件的第一个元素的值,参数接收一个函数,返回找到的值,找不到返回undefined,不改变原数组

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // 12

findIndex

从数组找出满足条件的第一个元素的索引值,参数接收一个函数,返回找到的元素的索引,找不到返回-1,不改变原数组

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3

every

测试数组内的所有元素是否都能通过某个指定函数的测试,参数接收一个函数,返回布尔值,不改变原数组

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold)); // true

some

测试数组内的某个元素是否能通过某个指定函数的测试,参数接收一个函数,返回布尔值,不改变原数组

const isBelowThreshold = (currentValue) => currentValue > 38;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.some(isBelowThreshold)); // true

map

将数组中的每个元素按照某种规则进行转换,参数接收一个函数,返回一个新的数组,不改变原数组

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1); // [2, 8, 18, 32]

join

将一个数组的所有元素连接成一个字符串并返回这个字符串,不改变原数组

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // "Fire,Air,Water"
console.log(elements.join('')); // "FireAirWater"
console.log(elements.join('-')); // "Fire-Air-Water"

concat

用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组

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

include

判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

const array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat')); // true
console.log(pets.includes('at')); // false

forEach

对数组每一个元素进行遍历操作,参数为一个函数,返回值为加工后的数组,改变原数组

const arraySparse = [1,3,,7];
let numCallbackRuns = 0;
arraySparse.forEach(function(element){
  console.log(element);
  numCallbackRuns++;
});
console.log("numCallbackRuns: ", numCallbackRuns);
// 1
// 3
// 7
// numCallbackRuns: 3

from

字符串变数组,伪数组变真数组,返回新数组,不改变原数组

// 从String生成数组
Array.from('foo'); // [ "f", "o", "o" ]

// 从Set生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set); // [ "foo", "bar", "baz" ]

// 从Map生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map); // [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values()); // ['a', 'b'];
Array.from(mapper.keys()); // ['1', '2'];

// 从类数组对象生成数组
function f() {
  return Array.from(arguments);
}
f(1, 2, 3); // [ 1, 2, 3 ]

// 使用箭头函数
Array.from([1, 2, 3], x => x + x); // [2, 4, 6]

indexOf

在数组中找到给定元素的第一个索引,返回索引值,找不到返回-1,不改变原数组

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1

slice

返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)); // ["camel", "duck"]
console.log(animals.slice(1, 5)); // ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2)); // ["duck", "elephant"]
console.log(animals.slice(2, -1)); // ["camel", "duck"]
console.log(animals.slice()); // ["ant", "bison", "camel", "duck", "elephant"]

splice

此方法能实现删除、修改和增加,返回值为被删除的元素组成的数组。此方法会改变原数组。

array.splice(start[, deleteCount[, item1[, item2[, ...]]]] )

start:指定修改的开始位置 deleteCount:表示要移除的数组元素的个数 item1,item2,...:要添加进数组的元素,从start位置开始,不指定将只删除数组元素

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months); // ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months); // ["Jan", "Feb", "March", "April", "May"]

reduce

此方法的功能非常强大,通过用作累加器使用,参数接收一个函数和一个初始值,返回单个汇总的值

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);
console.log(sumWithInitial); // 10

注:例子引用MDN