前言
数组是JavaScript中常见的操作,总结了一些数组常用的属性和用法,如有问题,欢迎大家指正~
创建数组
1. 创建数组并给数组元素赋值
let arr = new Array(); //创建一个默认数组,长度是0
arr[0] = 'aa';
let arr2 = new Array(5); //创建一个size长度的数组,注意Array的长度是可变的,所以不是上限,是长度, 创建数组指定了长度,但实际上所有情况下数组都是变长的,也就是说即使指定了长度为5,仍然可以将元素存储在规定长度以外的,注意:这时长度会随之改变。
2. 直接实例化
let arr = new Array('a'); //创建一个数组并赋初值
3. 创建,简写
let arr = ['a'];
数组属性
1. length属性
length属性表示数组的长度,因为数组的索引总是由0开始,所以一个数组的上下限分别是:0和length-1。
注意点:JavaScript数组中length属性是可变的,当length属性被设置的更大时,整个数组的状态事实上不会发生变化,仅仅是length属性变大;当length属性被设置得比原来小时,则原先数组中索引大于或等于length的元素的值全部被丢失。
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; // 定义数组长度为8
alert(arr.length) // 8
arr.length = 10 // 增大数组的长度
alert(arr.length) // 10 显示数据的长度已经变成10
alert(arr[7]) // 显示第8个元素值,是8
arr.length = 5 // 将数组的长度减少到5,索引等于或超过5的元素被丢弃
alert(arr[7]) // 显示第8个元素值,是undefined
arr.length = 10 // 数组长度恢复为10
alert(arr[7]) // 虽然长度恢复,此时数据已丢失,显示第8个元素值,是undefined
2. constructor属性
表示创建对象的函数。
object.constructor // object是对象或函数的名称。
说明:constructor属性是所有具有prototype的对象的成员。它们包括除Global和Math对象以外的所有JavaScript固有对象。constructor属性保存了对构造特定对象实例的函数的引用。
let arr = new Array();
arr.constructor === Array; // true
3. prototype属性
返回对象原型的引用,javascript中的每个对象都有prototype属性,说明:用prototype属性提供对象的类的一组基本功能。对象的新实例“继承”赋予该对象原型的操作。
Array.prototype属性表示 Array 构造函数的原型,并允许您向所有Array对象添加新的属性和方法
数组方法
1、Array.prototype.concat()
用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // ['a', 'b', 'c', 'd', 'e', 'f']
2、Array.prototype.copyWithin()
浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度
array.copyWithin(target, start, end)
// target 必需。复制到指定目标索引位置
// start 可选。元素复制的起始位置。
// end 可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。
const array1 = ['1', '2', '3', '4', '5'];
array1.copyWithin(0, 3, 4); // ["4", "2", "3", "4", "5"]
array1.copyWithin(1, 3); // ["4", "4", "5", "4", "5"]
3、Array.prototype.entries()
返回一个新的 Array Iterator 对象,该对象包含数组中每个索引的键/值对
var arr = ["a", "b", "c"];
var iterator = arr.entries();
iterator.next(); // {done: false, value: [0, 'a']}
iterator.next(); // {done: false, value: [1, 'b']}
iterator.next(); // {done: false, value: [2, 'c']}
iterator.next(); // {done: true, value: undefined}
可以使用for...of..
var arr = ['a', 'b', 'c'];
var iterator = arr.entries();
for (let e of iterator) {
console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']
4、Array.prototype.every()
测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值
array.every(function(element, index, array), thisValue)
element 必须。当前元素的值
index 可选,用于测试的当前值的索引。
array 可选 调用every的当前数组
thisValue 执行 callback 时使用的 this 值, 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold)); // true
若收到一个空数组,此方法在一切情况下都会返回 true
5、Array.prototype.fill()
用一个固定值填充一个数组中从起始索引到终止索引内的全部元素
const array1 = [1, 2, 3, 4];
array1.fill(0, 2, 4); // [1, 2, 0, 0]
array1.fill(5, 1); // [1, 5, 5, 5]
array1.fill(6); // [6, 6, 6, 6]
array.fill(value, start, end)
value 必需。填充的值。
start 可选。开始填充位置。
end 可选。停止填充位置 (默认为 array.length)
6、Array.prototype.filter()
创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); // ['exuberant', 'destruction', 'present']
array.filter(function(currentValue, index, arr), thisValue)
函数function 用来测试数组的每个元素的函数。返回 `true` 表示该元素通过测试,保留该元素,`false` 则不保留。它接受以下三个参数:
currentValue 必须。当前元素的值
index 正在处理的元素在数组中的索引。
arr 调用了 filter 的数组本身。
thisValue 执行 callback 时,用于 this 的值。 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"
7、Array.prototype.find()
返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // 12
array.find(function(currentValue, index, arr), thisValue)
8、Array.prototype.findIndex()
返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3
array.findIndex(function(currentValue, index, arr), thisValue)
9、Array.prototype.flat()
按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat()); // [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2)); // [0, 1, 2, [3, 4]]
arr.flat([depth]) depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。 返回: 一个包含将数组与子数组中所有元素的新数组。
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]
//使用 Infinity,可展开任意深度的嵌套数组
flat() 方法会移除数组中的空项:
var arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]
10、Array.prototype.flatMap()
使用映射函数映射每个元素,然后将结果压缩成一个新数组
array.findIndex(function(currentValue, index, arr), thisValue)
map 和 flatMap的比较
var arr1 = [1, 2, 3, 4];
arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]
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"]
11、Array.prototype.forEach()
对数组的每个元素执行一次给定的函数
array.forEach(function(currentValue, index, arr), thisValue)
除了抛出异常以外,没有办法中止或跳出 forEach() 循环。
若你需要提前终止循环,你可以使用:
for循环for...of/for...in循环Array.prototype.every()Array.prototype.some()Array.prototype.find()Array.prototype.findIndex()
12、Array.prototype.includes()
判断一个数组是否包含一个指定的值,如果包含则返回 true,否则返回 false
const array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
arr.includes(valueToFind, fromIndex)
valueToFind 需要查找的元素值
fromIndex 可选, 从fromIndex 索引处开始查找 valueToFind,如果为负值,则按升序从array.length + fromIndex的索引开始搜 (即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。
如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组。
var arr = ['a', 'b', 'c'];
arr.includes('c', 3); // false
arr.includes('c', 100); // false
如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97
var arr = ['a', 'b', 'c'];
arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false
13、Array.prototype.indexOf()
返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回 -1
const arr = [1, 2, 3, 4];
console.log(arr.indexOf(2)); // 1
arr.indexOf(searchElement, fromIndex)
searchElement 要查找的元素
fromIndex 可选 开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0.
var array = [2, 5, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
14、Array.prototype.join()
将一个数组的所有元素连接成一个字符串并返回这个字符串
arr.join(separator)
separator 可选 指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果缺省该值,数组元素用逗号(`,`)分隔。如果`separator`是空字符串(`""`),则所有元素之间都没有任何字符。
一个所有数组元素连接的字符串。如果 arr.length 为0,则返回空字符串。
如果一个元素为 undefined 或 null,它会被转换为空字符串。
15、Array.prototype.keys()
返回一个包含数组中每个索引键的 Array Iterator 对象
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// 0 1 2
arr.keys() 返回新的array迭代器对象
16、Array.prototype.lastIndexOf()
返回指定元素在数组中的最后一个的索引,如果不存在则返回 -1
arr.lastIndexOf(searchElement, fromIndex)
searchElement 要查找的元素
fromIndex 可选 从此位置开始逆向查找。默认为数组的长度减 1(`arr.length - 1`),即整个数组都被查找。如果该值大于或等于数组的长度,则整个数组会被查找。如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2, 3);
// index is 3
index = array.lastIndexOf(2, 2);
// index is 0
index = array.lastIndexOf(2, -2);
// index is 0
index = array.lastIndexOf(2, -1);
// index is 3
17、Array.prototype.map()
返回一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值
array.map(function(currentValue, index, arr), thisValue)
18、Array.prototype.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"]
如果你在一个空数组上调用 pop(),它返回 undefined。
19、Array.prototype.push()
将一个或多个元素添加到数组的末尾,并返回该数组的新长度
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 4
console.log(animals); // ['pigs', 'goats', 'sheep', 'cows']
当调用该方法时,新的 length 属性值将被返回。
20、Array.prototype.reduce()
对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值
其中 reduce()方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
用法:
array.reduce(function(previousValue, currentValue, currentIndex, arr), initialValue)
previousValue 必需。初始值, 或者计算结束后的返回值。
currentValue 必需,当前元素,数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
currentIndex 可选 当前元素的索引,数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
arr 可选 当前元素所属的数组对象,用于遍历的数组。
initialValue 可选 传递给函数的初始值, 作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。
例子:
const array1 = [1, 2, 3, 4];
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial); // 10
// reducer 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。
21、Array.prototype.reduceRight()
接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue)
);
console.log(array1); // [4, 5, 2, 3, 0, 1]
其中reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。
用法:
array.reduceRight(function(accumulator, currentValue, currentIndex, arr), initialValue)
accumulator 累加器:上一次调用回调函数时,回调函数返回的值。首次调用回调函数时,如果 initialValue 存在,累加器即为 initialValue,否则须为数组中的最后一个元素(详见下方 initialValue 处相关说明)。
currentValue 当前元素:当前被处理的元素。
currentIndex 可选 数组中当前被处理的元素的索引。
arr 可选 调用 reduceRight() 的数组。
initialValue 可选 首次调用 callback 函数时,累加器 accumulator 的值。如果未提供该初始值,则将使用数组中的最后一个元素,并跳过该元素。如果不给出初始值,则需保证数组不为空。
否则,在空数组上调用 reduce 或 reduceRight 且未提供初始值(例如 [].reduce( (acc, cur, idx, arr) => {} ) )的话,会导致类型错误 TypeError: reduce of empty array with no initial value。
22、Array.prototype.reverse()
将数组中元素的位置颠倒,并返回该数组。该方法会改变原数组
const array1 = ['one', 'two', 'three'];
console.log(array1); // ['one', 'two', 'three']
const reversed = array1.reverse();
console.log(reversed); // ['three', 'two', 'one']
console.log(array1); // ['three', 'two', 'one']
颠倒类数组中的元素
下例创造了一个类数组对象 a, 包含3个元素和一个 length 属性, 然后颠倒这个类数组对象。 reverse() 的调用返回一个颠倒后的类数组对象 a的引用。
const a = {0: 1, 1: 2, 2: 3, length: 3};
console.log(a); // {0: 1, 1: 2, 2: 3, length: 3}
Array.prototype.reverse.call(a); //same syntax for using apply()
console.log(a); // {0: 3, 1: 2, 2: 1, length: 3}
23、Array.prototype.shift()
从数组中删除第一个元素,并返回该元素的值, 如果数组为空则返回undefined。
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); // [2, 3]
console.log(firstElement); // 1
24、Array.prototype.slice()
提取源数组的一部分并返回一个新数组
arr.slice(begin, end)
begin 可选 提取起始处的索引(从 0 开始),从该索引开始提取原数组元素。如果该参数为负数,则表示从原数组中的倒数第几个元素开始提取,slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)。如果省略 begin,则 slice 从索引 0 开始。如果 begin 超出原数组的索引范围,则会返回空数组。
end 可选 提取终止处的索引(从 0 开始),在该索引处结束提取原数组元素。slice 会提取原数组中索引从 begin 到 end 的所有元素(包含 begin,但不包含 end)。slice(1,4) 会提取原数组中从第二个元素开始一直到第四个元素的所有元素 (索引为 1, 2, 3的元素)。如果该参数为负数, 则它表示在原数组中的倒数第几个元素结束抽取。 slice(-2,-1) 表示抽取了原数组中的倒数第二个元素到最后一个元素(不包含最后一个元素,也就是只有倒数第二个元素)。如果 end 被省略,则 slice 会一直提取到原数组末尾。如果 end 大于数组的长度,slice 也会一直提取到原数组末尾。
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']
25、Array.prototype.some()
测试数组中是不是至少有一个元素通过了被提供的函数测试
如果用一个空数组进行测试,在任何情况下它返回的都是false。
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even)); // true
array.some(function(element, index, array), thisValue)
element 必须。数组中正在处理的元素。
index 可选,数组中正在处理的元素的索引值。
array 可选 调用some的当前数组
thisValue 执行 callback 时使用的 this 值, 可选。
数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false。
26、Array.prototype.sort()
对数组元素进行原地排序并返回此数组
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months); // ['Dec', 'Feb', 'Jan', 'March']
const array1 = [1, 30, 4, 21, 55555];
array1.sort();
console.log(array1); // [1, 21, 30, 4, 55555]
arr.sort(compareFunction)
compareFunction 用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。
firstEl 第一个用于比较的元素。
secondEl 第二个用于比较的元素。
排序后的数组。请注意,数组已原地排序,并且不进行复制。
27、Array.prototype.splice()
通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months); // ['Jan', 'Feb', 'March', 'April', 'June']
months.splice(4, 1, 'May');
console.log(months); // ['Jan', 'Feb', 'March', 'April', 'May']
array.splice(start, deleteCount, item1, item2, ...)
start 指定修改的开始位置(从0计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从-1计数,这意味着-n是倒数第n个元素并且等价于array.length-n);如果负数的绝对值大于数组的长度,则表示开始位置为第0位。
deleteCount 可选 整数,表示要移除的数组元素的个数。如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)。如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是说,如果它大于或者等于start之后的所有元素的数量),那么start之后数组的所有元素都会被删除。如果 deleteCount 是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。
item1, item2, ... 可选 要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。
由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。
28、Array.prototype.toLocaleString()
返回一个字符串表示数组中的元素。数组中的元素将使用各自的 Object.prototype.toLocaleString()方法转成字符串
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString); // 1,a,12/21/1997, 2:12:00 PM
arr.toLocaleString(locales, options);
locales 可选 带有BCP 47语言标记的字符串或字符串数组,关于locales参数的形式与解释,请看Intl页面。
options 可选 一个可配置属性的对象,对于数字 Number.prototype.toLocaleString(),对于日期Date.prototype.toLocaleString().
Intl页面 Number.prototype.toLocaleString() Date.prototype.toLocaleString()
var prices = ['¥7', 500, 8123, 12];
prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
// '¥7,¥500,¥8,123,¥12'
29、Array.prototype.toString()
返回一个字符串表示指定的数组及其元素。数组中的元素将使用各自的 Object.prototype.toString()方法转成字符串
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString()); // 1,2,a,1a
arr.toString() 一个表示指定的数组及其元素的字符串。
30、Array.prototype.unshift()
将一个或多个元素添加到数组的头部,并返回该数组的新长度
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 5
console.log(array1); // [4, 5, 1, 2, 3]
arr.unshift(element1, ..., elementN)
elementN 要添加到数组开头的元素或多个元素。
let arr = [1, 2];
arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]
arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]
arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]
arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
31、Array.prototype.values()
返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// a b c