JavaScript Array 的 1 个属性,35 个方法

前言

这周呢,彻底学习一下 Array 的所有方法。学习地址 MDN,里面还有各个函数实现的源码!数组作为 JavaScript 的一种特殊的对象类型,与 Number,Boolean,Null,String,Undefined,Symbol 七大数据类型有所不一样。了解 Array 的所有方法,能帮助我们最快找到适合自己的函数。

Create an Array

创建一个数组很简单,直接赋值,或者使用 [] 创建空数组

1
2
var fruits = ['Apple', 'Banana'];
console.log(fruits.length); // 2

Properties

Array.length
1
2
3
4
5
6
var clothing = ['shoes', 'shirts', 'socks', 'sweaters'];

console.log(clothing.length);
// expected output: 4

var array = new Array(2)

Methods

首先看一下 Array 的三个静态方法
#####1. Array.from()
Array.from() 方法从类似数组或可迭代的对象创建一个新的,浅拷贝的 Array 实例,或者从 {length: 3} 对象中创建固定长度的 undefined 数组

Array.from(arrayLike[, mapFn[, thisArg]])

1
2
3
4
5
6
7
8
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

console.log(Array.from({length: 3}));
// expected output: Array [undefined, undefined, undefined]
2. Array.isArray()

Array.isArray() 方法确定传递的值是否为 Array,由于 typeof Array = ‘object’ ,所以判断是否是一个数组使用 isArray 才可以

Array.isArray(value)

1
2
3
4
Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar'); // false
Array.isArray(undefined); // false
3. Array.of()

Array.of() 方法从可变数量的参数创建一个新的Array实例,无论参数的数量或类型如何
注意它与构造函数的不同之处

Array.of(element0[, element1[, …[, elementN]]])

1
2
3
4
5
Array.of(7);       // [7] 
Array.of(1, 2, 3); // [1, 2, 3]

Array(7); // array of 7 empty slots
Array(1, 2, 3); // [1, 2, 3]

接下来看 Array 的对象方法

4. Array.prototype.concat()

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

var new_array = old_array.concat([value1[, value2[, …[, valueN]]]])

1
2
3
4
5
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
5. Array.prototype.copyWithin()

copyWithin() 方法浅析将数组的一部分复制到同一数组中的另一个位置,并返回它而不修改其长度

arr.copyWithin(target[, start[, end]])

1
2
3
4
5
6
7
8
9
var array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
6. Array.prototype.entries()

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

array.entries()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]

// 使用 for of 遍历
var a = ['a', 'b', 'c'];
var iterator = a.entries();

for (let e of iterator) {
console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']
7. Array.prototype.every()

every() 方法测试数组中的所有元素是否都通过了由提供的函数实现的测试。 它返回一个布尔值

arr.every(callback(element[, index[, array]])[, thisArg])

1
2
3
4
5
6
7
8
function isBelowThreshold(currentValue) {
return currentValue < 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
8. Array.prototype.fill()

fill() 方法使用静态值从开始索引(默认为零)到结束索引(默认数组长度)填充(修改)数组的所有元素。 它返回修改后的数组,原数组会改变~

arr.fill(value[, start[, end]])

1
2
3
4
5
6
7
8
9
10
11
12
 var array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
9. Array.prototype.filter()

filter() 方法创建一个新数组,其中包含所有传递由提供的函数实现的测试的元素

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

1
2
3
4
5
6
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
10. Array.prototype.find()

find() 方法返回数组中第一个满足提供的测试函数的元素的值。 否则返回undefined

arr.find(callback(element[, index[, array]])[, thisArg])

1
2
3
4
5
6
7
8
var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
return element > 10;
});

console.log(found);
// expected output: 12
11. Array.prototype.findIndex()

findIndex() 方法返回数组中第一个满足提供的测试函数的元素的索引。 否则,它返回-1,表示没有元素通过测试

arr.findIndex(callback(element[, index[, array]])[, thisArg])

1
2
3
4
5
6
7
var array1 = [5, 12, 8, 130, 44];

function isLargeNumber(element) {
return element > 13;
}

console.log(array1.findIndex(isLargeNumber));
12. Array.prototype.flat()

flat() 方法创建一个新数组,所有子数组元素以递归方式连接到指定的深度。

var newArray = arr.flat([depth]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

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

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

var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
13. Array.prototype.flatMap()

flatMap() 方法首先使用映射函数映射每个元素,然后将结果展平为新数组。 它与map()后跟深度为1的flat()相同,但flatMap()通常非常有用,因为将两者合并到一个方法中效率稍高

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])

1
2
3
4
5
6
7
let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]
14. Array.prototype.forEach()

forEach() 方法为每个数组元素执行一次提供的函数

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);

1
2
3
4
5
6
7
8
9
var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
console.log(element);
});

// expected output: "a"
// expected output: "b"
// expected output: "c"
15. Array.prototype.includes()

includes() 方法确定数组是否在其条目中包含某个值,并在适当时返回true或false

arr.includes(valueToFind[, fromIndex])

1
2
3
4
5
6
7
8
9
10
11
12
var array1 = [1, 2, 3];

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

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

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false
16. Array.prototype.indexOf()

indexOf() 方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1

arr.indexOf(searchElement[, fromIndex])

1
2
3
4
5
6
7
8
9
10
11
var 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
17. Array.prototype.join()

join() 方法通过连接数组(或类数组对象)中的所有元素(用逗号或指定的分隔符字符串分隔)来创建并返回一个新字符串。 如果数组只有一个项目,那么将返回该项目而不使用分隔符

arr.join([separator])

1
2
3
4
5
6
7
8
9
10
ar elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
18. Array.prototype.keys()

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

1
2
3
4
5
6
var array1 = ['a', 'b', 'c'];
var iterator = array1.keys();

for (let key of iterator) {
console.log(key); // expected output: 0 1 2
}
19. Array.prototype.lastIndexOf()

lastIndexOf() 方法返回可在数组中找到给定元素的最后一个索引,如果不存在则返回-1。 从fromIndex开始向后搜索数组

arr.lastIndexOf(searchElement[, fromIndex])

1
2
3
4
5
6
7
var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Penguin', 1));
// expected output: -1
20. Array.prototype.map()

map() 方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])

1
2
3
4
5
6
7
var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
21. Array.prototype.pop()

pop() 方法从数组中删除最后一个元素并返回该元素。 此方法更改数组的长度。

arr.pop()

1
2
3
4
5
6
7
8
9
10
11
12
var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
22. Array.prototype.push()

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

arr.push(element1[, …[, elementN]])

1
2
3
4
5
6
7
8
9
10
11
12
var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens');

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"]
23. Array.prototype.reduce()

reduce() 方法在数组的每个元素上执行reducer函数(您提供),从而产生单个输出值

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

1
2
3
4
5
6
7
8
9
10
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
24. Array.prototype.reduceRight()

reduceRight() 方法对累加器和数组的每个值(从右到左)应用函数以将其减少为单个值

arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])

1
2
3
4
5
6
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
25. Array.prototype.reverse()

reverse() 方法将数组反转到位。 第一个数组元素成为最后一个,最后一个数组元素成为第一个

a.reverse()

1
2
3
4
5
6
7
8
9
10
11
12
var array1 = ['one', 'two', 'three'];
console.log('array1: ', array1);
// expected output: Array ['one', 'two', 'three']

var reversed = array1.reverse();
console.log('reversed: ', reversed);
// expected output: Array ['three', 'two', 'one']

/* Careful: reverse is destructive. It also changes
the original array */
console.log('array1: ', array1);
// expected output: Array ['three', 'two', 'one']
26. Array.prototype.shift()

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

arr.shift()

1
2
3
4
5
6
7
8
9
var array1 = [1, 2, 3];

var firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1
27. Array.prototype.slice()

slice() 方法将数组的一部分的浅表副本返回到从头到尾选择的新数组对象(不包括结尾),其中begin和end表示该数组中项的索引。 原始数组不会被修改

arr.slice([begin[, end]])

1
2
3
4
5
6
7
8
9
10
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

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

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
28. # Array.prototype.some()

some() 方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。 它返回一个布尔值

arr.some(callback(element[, index[, array]])[, thisArg])

1
2
3
4
5
6
7
8
9
var array = [1, 2, 3, 4, 5];

var even = function(element) {
// checks whether an element is even
return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true
29. Array.prototype.sort()

sort() 方法对数组中的元素进行排序并返回已排序的数组。 默认排序顺序是在将元素转换为字符串,然后比较它们的UTF-16代码单元值序列时构建的。

由于取决于实现,因此无法保证排序的时间和空间复杂性。

arr.sort([compareFunction])

1
2
3
4
5
6
7
8
9
var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
30. Array.prototype.splice()

splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容

var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, …]]]])

1
2
3
4
5
6
7
8
9
10
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
31. Array.prototype.unshift()

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

arr.unshift(element1[, …[, elementN]])

1
2
3
4
5
6
7
var array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
32. Array.prototype.values()

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

arr.values()

1
2
3
4
5
6
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
console.log(value); // expected output: "a" "b" "c"
}
33. Array.prototype.toLocaleString()

toLocaleString() 方法返回表示数组元素的字符串。 使用toLocaleString方法将元素转换为字符串,并且这些字符串由特定于语言环境的字符串(例如逗号“,”)分隔

arr.toLocaleString([locales[, options]]);

1
2
3
4
5
6
var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
var localeString = array1.toLocaleString('en', {timeZone: "UTC"});

console.log(localeString);
// expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
34. Array.prototype.toString()

toString() 方法返回表示指定数组及其元素的字符串

arr.toString()

1
2
3
4
var array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"
35. Array.prototype@@iterator

@@iterator 属性的初始值与values()属性的初始值是相同的函数对象。

arrSymbol.iterator

1
2
3
4
5
6
7
8
var arr = ['a', 'b', 'c', 'd', 'e'];
var eArr = arr[Symbol.iterator]();
// your browser must support for..of loop
// and let-scoped variables in for loops
// const and var could also be used
for (let letter of eArr) {
console.log(letter);
}