Skip to content

Latest commit

 

History

History
200 lines (155 loc) · 5.1 KB

09数组的扩展.md

File metadata and controls

200 lines (155 loc) · 5.1 KB

数组的扩展

1.扩展运算符

主要用于函数调用。只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错。

(...[1, 2])
// Uncaught SyntaxError: Unexpected number

console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number

console.log(...[1, 2])
// 1 2

应用

  • 替代函数的 apply 方法
  • 复制数组
  • 合并数组(浅拷贝)
  • 与解构赋值结合(只能放最后一位)
  • 字符串转数组(能够识别四个字节的 Unicode 字符)
  • 实现了 Iterator 接口的对象:类数组(无 Iterator 属性报错)、Map、Set、Generator)
// 替代函数的 apply 方法
Math.max.apply(null, [14, 3, 77]) // ES5 的写法
Math.max(...[14, 3, 77]) // ES6 的写法

//  apply 方法
const a1 = [1, 2];
const a2 = [...a1]; // 写法一
const [...a2] = a1; // 写法二

// 合并数组(浅拷贝)
const arr1 = ['a', 'b'];
const arr2 = ['c']
const arr3 = ['d', 'e'];
arr1.concat(arr2, arr3)  // ES5 的合并数组
[...arr1, ...arr2, ...arr3]  // ES6 的合并数组

// 与解构赋值结合(只能放最后一位)
const [first, ...rest] = [1, 2, 3, 4, 5];
const [...rest, first] = [1, 2, 3, 4, 5]; //报错

// 字符串转数组(能够识别四个字节的 Unicode 字符)
let str = 'x\uD83D\uDE80y';
str.split('').reverse().join('')  // 'y\uDE80\uD83Dx'
[...str].reverse().join('')       // 'y\uD83D\uDE80x'

// 实现了 Iterator 接口的对象(类数组、Map、Set、Generator)
//类数组 
let nodeList = document.querySelectorAll('div');
let array = [...nodeList]

// Map
let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]

// Generator
const go = function*(){
  yield 1;
  yield 2;
  yield 3;
};
[...go()] // [1, 2, 3]

2.Array.from()

用于将两类对象转为真正的数组

  1. 参数一:对象
    1. 类数组对象(含length的对象、argument对象)
    2. 可遍历(iterable)的对象(数组、字符串、Set、Mat、Generator)
  2. 参数二:函数,实现map功能
  3. 参数三:上下文
Array.from({length: 3}, (v, i) => i)

// 能够正确处理 Unicode 字符
Array.from('\uD842\uDFB7').length;

3.Array.of()

Array.of方法用于将一组值,转换为数组(弥补数组构造函数Array()的不足)。

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

Array.of(3) // [3]
Array.of(3, 11, 8) // [3,11,8]

数组实例

  • copyWithin(开始替换数据,开始读取数据,到该位置前停止读取数据):将指定位置的成员复制到其他位置(会修改当前数组)
  • find():返回第一个符合条件的数组成员
  • findIndex():返回第一个符合条件的数组成员的位置
  • fill(value, start, end):填充一个数组(如果填充的类型为对象,那么被赋值的是同一个内存地址的对象,而不是深拷贝对象)
  • entries():对键值对的遍历
  • keys():对键名的遍历
  • values():对键值的遍历
  • includes(value, start, end):某个数组是否包含给定的值
  • flat(number):将嵌套的数组“拉平”
  • flatMap(fn, start, this):执行fn(相当于map函数),再将嵌套的数组“拉平”
// copyWithin
[1, 2, 3, 4, 5].copyWithin(0, -2, -1) // [4, 2, 3, 4, 5]
[1, 2, 3, 4, 5].copyWithin(0, -4, -1) // [2, 3, 4, 4, 5]

// find
[1, 4, -5, 10].find(n => n < 0) // 4

// findIndex
[1, 4, -5, 10].findIndex(n => n === 4) // 1

// fill
['a', 'b', 'c'].fill(7, 1, 2) // ['a', 7, 'c']

// entries
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']

// includes
[NaN].includes(NaN) // true
[NaN].indexOf(NaN) // -1

// flat
[1, [2, [3]]].flat(Infinity) // [1, 2, 3]

数组的空位

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(['a',,'b']) // [ "a", undefined, "b" ]

[...['a',,'b']] // [ "a", undefined, "b" ]

[,'a','b',,].copyWithin(2,0) // [,"a",,"a"]

new Array(3).fill('a') // ["a","a","a"]

for (let i of [, ,]) console.log(1)
// 1
// 1

// 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