# 数组
# 扩展运算符
扩展运算符(spread)是三个点(...)。它好比 rest
参数的逆运算,将一个数组转为用逗号分隔的参数序列。扩展运算符有应用:
替代函数的 apply 方法
由于扩展运算符可以展开数组,所以不再需要 apply
方法,将数组转为函数的参数了
// ES5 的写法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f.apply(null, args);
// ES6的写法
function f(x, y, z) {
// ...
}
let args = [0, 1, 2];
f(...args);
复制数组
数组是复合的数据类型,直接复制的话,只是复制了指向底层数据结构的指针,而不是克隆一个全新的数组
// ES5
const a1 = [1, 2];
const a2 = a1.concat();
a2[0] = 2;
a1 // [1, 2]
// ES6
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
与解构赋值结合
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // []
const [first, ...rest] = ["foo"];
first // "foo"
rest // []
字符串
扩展运算符还可以将字符串转为真正的数组
[...'hello']
// [ "h", "e", "l", "l", "o" ]
// 扩展运算符能够正确识别四个字节的 Unicode 字符
'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3
实现了 Iterator 接口的对象
任何定义了遍历器(Iterator)接口的对象(参阅 Iterator 一章),都可以用扩展运算符转为真正的数组。
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
Number.prototype[Symbol.iterator] = function*() {
let i = 0;
let num = this.valueOf();
while (i < num) {
yield i++;
}
}
console.log([...5])
对于那些没有部署 Iterator 接口的类似数组的对象,扩展运算符就无法将其转为真正的数组
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// TypeError: Cannot spread non-iterable object.
let arr = [...arrayLike];
上面代码中,arrayLike
是一个类似数组的对象,但是没有部署 Iterator 接口,扩展运算符就会报错。这时,可以改为使用 Array.from
方法将 arrayLike
转为真正的数组。
# 数组创建
# Array.of
Array.of()
将参数中所有值作为元素形成数组
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array.of
方法可以弥补数组构造函数 Array()
的不足。因为参数个数的不同,会导致 Array()
的行为有差异
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Array.of
基本上可以用来替代 Array()
或 new Array()
,并且不存在由于参数不同而导致的重载。它的行为非常统一
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]
Array.of
总是返回参数值组成的数组。如果没有参数,就返回一个空数组
# Array.from()
Array.from()
方法从一个类似数组或可迭代对象(iterable)创建一个新的,浅拷贝的数组实例
Array.from(arrayLike[, mapFn[, thisArg]])
可接收三个参数
arrayLike
: 想要转换成数组的伪数组对象或可迭代对象mapFn
: 如果指定了该参数,新数组中的每个元素会执行该回调函数, 类似map
方法thisArg
: 可选参数,执行回调函数mapFn
时this
对象。
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
// NodeList对象
let ps = document.querySelectorAll('p');
Array.from(ps).filter(p => {
return p.textContent.length > 100;
});
// arguments对象
function foo() {
var args = Array.from(arguments);
// ...
}
只要是部署了 Iterator 接口的数据结构,Array.from
都能将其转为数组
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
上面代码中,字符串和 Set 结构都具有 Iterator 接口,因此可以被 Array.from
转为真正的数组
Array.from和扩展运算符的区别
扩展运算符(...
)也可以将某些数据结构转为数组
// arguments对象
function foo() {
const args = [...arguments];
}
// NodeList对象
[...document.querySelectorAll('div')]
扩展运算符: 扩展运算符背后调用的是遍历器接口(Symbol.iterator),如果一个对象没有部署这个接口,就无法转换
Array.from
: 支持两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象,所谓类似数组的对象,本质特征只有一点,即必须有 length
属性
Array.from({ length: 3 });
// [ undefined, undefined, undefined ]
Array.from
还可以接受第二个参数,作用类似于数组的 map
方法,用来对每个元素进行处理,将处理后的值放入返回的数组
Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);
Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
Array.from()
的另一个应用是,将字符串转为数组,然后返回字符串的长度。因为它能正确处理各种 Unicode 字符,可以避免 JavaScript 将大于 \uFFFF
的 Unicode 字符,算作两个字符的 bug
# 数组遍历方法
# entries(),keys()和values()
entries()
,keys()
和 values()
用于遍历数组。它们都返回一个遍历器对象
entries()
: 对键值对的遍历keys()
: 键名的遍历values()
: 对键值的遍历
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
如果不使用 for...of
循环,可以手动调用遍历器对象的 next
方法,进行遍历
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
# for...of
一个数据结构只要部署了 Symbol.iterator
属性,就被视为具有 iterator
接口,就可以用 for...of
循环遍历它的成员。也就是说,for...of
循环内部调用的是数据结构的 Symbol.iterator
方法。
for...of
循环可以使用的范围包括 数组、Set
和 Map
结构、某些类似数组的对象(比如 arguments
对象、DOM NodeList
对象)、 Generator
对象,以及字符串。
对于普通的对象,for...of
结构不能直接使用,会报错,必须部署了 Iterator 接口后才能使用
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
for (let [key, value] of entries(obj)) {
console.log(key, '->', value);
}
// a -> 1
// b -> 2
// c -> 3
# 遍历方法集合
for
for (var index = 0; index < myArray.length; index++) {
console.log(myArray[index]);
}
因此数组提供内置的 forEach
方法
forEach
myArray.forEach(function (value) {
console.log(value);
});
forEach
循环无法中途跳出,break
命令或 return
命令都不能奏效
for...in
for...in
循环可以遍历数组的键名
for (var index in myArray) {
console.log(myArray[index]);
}
for...in
循环有几个缺点
数组的键名是数字,但是
for...in
循环是以字符串作为键名 “0”、“1”、“2” 等等for...in
循环不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键某些情况下,
for...in
循环会以任意顺序遍历键名
总之,for...in
循环主要是为遍历对象而设计的,不适用于遍历数组
for...of
for (let value of myArray) {
console.log(value);
}
for...of
的特点:
有着同
for...in
一样的简洁语法,但是没有for...in
那些缺点不同于
forEach
方法,它可以与break
、continue
和return
配合使用提供了遍历所有数据结构的统一操作接口
下面是一个使用 break
语句,跳出 for...of
循环的例子
for (var n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
# 数组元素查找
ES6 新增的数组元素查找方法有 find
, findIdex
,includes
# find()
数组实例的 find
方法,用于找出第一个符合条件的数组成员
find(fn, targe)
接收两个参数
fn(value, index, arr)
: 处理当前值的回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true
的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined
, 这个回调接收三个参数value
: 当前的值index
: 当前的位置arr
: 原数组
targe
: 绑定回调函数的this
对象
let person = {name: 'John', age: 9};
[1, 5, 10, 15].find(function(value, index, arr) {
return value > this.age;
}) // 10
# findIndex
数组实例的 findIndex
方法的用法与 find
方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回 -1
,用法跟 find
一样
find
和 findIndex
这两个方法都可以发现 NaN
,弥补了数组的 indexOf
方法的不足
[NaN].indexOf(NaN)
// -1
[NaN].findIndex(y => Object.is(NaN, y))
// 0
上面代码中,indexOf
方法无法识别数组的NaN成员,但是 findIndex
方法可以借助 Object.is
方法做到
# includes
Array.prototype.includes(value, start)
方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的 includes
方法类似
includes(value, start)
接收两个参数:
value
: 要搜索的值start
: 表示搜索的起始位置,默认为0
, 如果为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4
,但数组长度为3
),则会重置为从0
开始
includes
和 indexOf
的区别:
includes
和 indexOf
都使用 while
循环做遍历
includes
比较值的方式是:
1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Number, then
1. If x is NaN and y is NaN, return true.
1. If x is +0 and y is -0, return true.
1. If x is -0 and y is +0, return true.
1. If x is the same Number value as y, return true.
3. Return false.
4. Return SameValueNonNumber(x, y).
indexOf
内部使用严格相等运算符( ===
)进行判断,也因此 indexOf
会导致对 NaN
的误判
[NaN].indexOf(NaN)
// -1
[NaN].includes(NaN)
// true
ES5 查找数组元素的方法有: indexOf()
, every()
和 some()
every()
和 some()
和 find
接收的参数和用法都一致
# 数组结构打平flat(),flatMap()
flat()
方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。该方法返回一个新数组,对原数据没有影响
var newArray = arr.flat([depth])
depth
: 指定要提取嵌套数组的结构深度,默认值为1
,Infinity
表示无限层级
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]
//使用 Infinity,可展开任意深度的嵌套数组
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]
flatMap()
方法对原数组的每个成员执行一个函数(相当于执行 Array.prototype.map()
),然后对返回值组成的数组执行 flat()
方法。该方法返回一个新数组,不改变原数组
flatMap(callback, thisArg)
接收的参数:
callback
: 处理当前值的回调函数, 回调函数可以传入三个参数:currentValue
: 当前正在数组中处理的元素index
: 选的。数组中正在处理的当前元素的索引array
: 可选的。被调用的 map 数组
thisArg
: 可选的。执行callback
函数时 使用的this
值
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]]
# copyWithin()
和fill()
# copyWithin()
数组实例的 copyWithin()
方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
Array.prototype.copyWithin(target, start = 0, end = this.length)
它接受三个参数:
target
(必需):从该位置开始替换数据。如果为负值,表示倒数start
(可选):从该位置开始读取数据,默认为0
。如果为负值,表示从末尾开始计算end
(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
上面代码表示将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2
其它例子:
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}
// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]
// 对于没有部署 TypedArray 的 copyWithin 方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
# fill()
fill
方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引
arr.fill(value[, start[, end]])
接收的参数
value
: 用来填充数组元素的值start
: 可选,起始索引,默认值为0。end
: 可选,终止索引,默认值为this.length
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
// Objects by reference.
var arr = Array(3).fill({}) // [{}, {}, {}];
// 需要注意如果fill的参数为引用类型,会导致都执行都一个引用类型
// 如 arr[0] === arr[1] 为true
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
# 数组的空位
ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位
forEach()
,filter()
,reduce()
,every()
和some()
都会跳过空位map()
会跳过空位,但会保留这个值join()
和toString()
会将空位视为undefined
,而undefined
和null
会被处理成空字符串
// forEach方法
[,'a'].forEach((x,i) => console.log(i)); // 1
// filter方法
['a',,'b'].filter(x => true) // ['a','b']
// every方法
[,'a'].every(x => x==='a') // true
// reduce方法
[1,,2].reduce((x,y) => x+y) // 3
// some方法
[,'a'].some(x => x !== 'a') // false
// map方法
[,'a'].map(x => 1) // [,1]
// join方法
[,'a',undefined,null].join('#') // "#a##"
// toString方法
[,'a',undefined,null].toString() // ",a,,"
ES6 则是明确将空位转为 undefined
// Array.from方法会将数组的空位,转为undefined,也就是说,这个方法不会忽略空位
Array.from(['a',,'b']) // [ "a", undefined, "b" ]
// 扩展运算符(...)也会将空位转为undefined
[...['a',,'b']] // [ "a", undefined, "b" ]
// copyWithin()会连空位一起拷贝
[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]
// fill()会将空位视为正常的数组位置
new Array(3).fill('a') // ["a","a","a"]
// for...of循环也会遍历空位
let arr = [, ,];
for (let i of arr) {
console.log(1);
}
// 1
// 1
entries()
、keys()
、values()
、find()
和 findIndex()
会将空位处理成 undefined
// entries()
[...[,'a'].entries()] // [[0,undefined], [1,"a"]]
// keys()
[...[,'a'].keys()] // [0,1]
// values()
[...[,'a'].values()] // [undefined,"a"]
// find()
[,'a'].find(x => true) // undefined
// findIndex()
[,'a'].findIndex(x => true) // 0
# ES5数组方法
# map
map()
方法根据一人数组创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值
map()
接收两个参数
callback
: 生成新数组元素的函数,使用三个参数:currentValue
:callback
数组中正在处理的当前元素index
:callback
数组中正在处理的当前元素的索引array
:map
方法调用的数组
thisArg
: 执行callback
函数时值被用作this
# filter
filter()
方法创建一个新数组, 过滤使用
参数和 map
一致,返回值是通过过滤的数组, 没有则为空数组
# every
every()
方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值
参数和 map
一致,返回值是通过过滤的数组, 没有则为空数组
# some
some()
方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值
参数和 map
一致,返回值是通过过滤的数组, 没有则为空数组
# reducer
reduce()
方法对数组中的每个元素执行一个由您提供的 reducer
函数(升序执行),将其结果汇总为单个返回值
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
函数接收4个参数:
callback
: 执行数组中每个值 (如果没有提供initialValue
则第一个值除外)的函数,包含四个参数accumulator
: 累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue
currentValue
: 数组中正在处理的元素index
: 可选, 数组中正在处理的当前元素的索引array
: 可选,调用reduce()的数组
initialValue
: 作为第一次调用callback
函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用reduce
将报错
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
})
# 数组方法的性能对比
# for,map和forEach性能
性能: for
> forEach
> map
for
循环当然是最简单的,因为它没有任何额外的函数调用栈和上下文forEach
其次,因为它其实比我们想象得要复杂一些,它的函数签名实际上是array.forEach(function(currentValue, index, arr), thisValue)
它不是普通的for
循环的语法糖,还有诸多参数和上下文需要在执行的时候考虑进来,这里可能拖慢性能;map
最慢,因为它的返回值是一个等长的全新的数组,数组创建和赋值产生的性能开销很大
但是 for/for-in/for-of
这类遍历方法很有可能改变外部的其他变量,这本身就会有一定风险,看起来是不可控的,代码也不优雅
# for in 和for of的区别
for in
for...in
语句以任意顺序遍历一个对象的除 Symbol
以外的可枚举属性,可用于数组也可以用于对象
使用 for...in
要注意的问题:
遍历所有属性,不仅是自身属性,也包括原型链上的所有属性
var obj = {a:1, c: 3, b:2}; obj.__proto__.d = 4 for (var prop in obj) { console.log("obj." + prop + " = " + obj[prop]); } // obj.a = 1 // obj.c = 3 // obj.b = 2 // obj.d = 4
index
索引为字符串型数字,不能直接进行几何运算必须按特定顺序遍历,先遍历所有数字键,然后按照创建属性的顺序遍历剩下的
var obj = {a:1, c: 3, b:2, 1:3}; for (var prop in obj) { console.log("obj." + prop + " = " + obj[prop]); } // obj.1 = 3 // obj.a = 1 // obj.c = 3 // obj.b = 2
会忽略
enumerable
为false
的属性
for...of
for...of
语句用于可迭代的对象上,即实现了 遍历器Iterator
的实例(包括 Array
,Map
,Set
,String
,TypedArray
,arguments
对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
for...of
不能用于对象中, 因为对象没有实现遍历器 Iterator
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"
for...of
会修改源数据中的值
let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
for...of
与 for...in
的区别
for...in
语句以任意顺序迭代对象的可枚举属性for...of
语句遍历可迭代对象定义要迭代的数据
迭代String
let iterable = "boo";
for (let value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
迭代Map
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let entry of iterable) {
console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
关闭迭代器
for...of
可以像 for
循环那样,使用break
, throw
, continue
这些循环控制语句