ES6数组的扩展

一、扩展运算符(…)

1、含义:一个数组转为用逗号分隔的参数序列。

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

console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
  • 可用于函数的调用
例1:
function add(x, y) {
    
    
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42

例2:
function f(v,w,x,y,z){
    
     
    return [v,w,x,y,z];
}
const args = [0,1];
console.log( ...f(-1,...args,...[2],3) );    //-1 0 1 2 3
  • 用于表达式
const x = 4;
const arr = [...(x>0?['a']:[]),'b'];
console.log(...arr);     //a b
  • 如果数组后面是空数组,则空数组会被忽视
[...[], 1]
// [1]

2、替代函数的 apply 方法

  • 可以直接把数组转化为参数列表
把数组2放到数组1
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);

3、扩展运算符的应用

(1)复制数组

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

(2)合并数组

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

(3)与解构赋值结合

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

(4)字符串

  • 把字符串转换为数组
 [...'hello']
// [ "h", "e", "l", "l", "o" ]
  • 扩展运算符可以正确识别四个字节的 Unicode 字符。
function length(str) {
    
    
  return [...str].length;
}

length('x\uD83D\uDE80y') // 3

(5)实现了 Iterator 接口的对象

  • 任何定义了遍历器接口的对象,都可以用扩展运算符转为真正的数组。
Number.prototype[Symbol.iterator] = function*() {
    
    
  let i = 0;
  let num = this.valueOf();
  while (i < num) {
    
    
    yield i++;
  }
}

console.log([...5]) // [0, 1, 2, 3, 4]

(6)Map 和 Set 结构,Generator 函数

  • 扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。
let map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

let arr = [...map.keys()]; // [1, 2, 3]

二、Array.from()

Array.from方法用于将两类对象转为真正的数组:类似数组的对象和可遍历的对象.
(1)类似数组的对象

let arrayLike = {
    
    
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

三、Array.of()

用法:用于将一组值,转换为数组。

Array.of基本上可以用来替代Array()或new Array(),并且不存在由于参数不同而导致的重载。它的行为非常统一。

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

四、数组实例的copyWithin()

1.用法:在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
2.接收的三个参数:

Array.prototype.copyWithin(target, start = 0, end = this.length)

target(必需):从该位置开始替换数据。如果为负值,表示倒数。
start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。

  • 这三个参数都应该是数值,如果不是,会转换为数值。
例子:
// 将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]

五、数组实例的find()和findIndex()

1、find()方法

用法:用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。

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

2、findIndex()方法

用法:返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {
    
    
  return value > 9;
}) // 2
  • 这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。且这两个函数都可以发现NaN,弥补了数组的indexOf方法的不足。
function f(v){
    
    
  return v > this.age;
}
let person = {
    
    name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26

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

[NaN].findIndex(y => Object.is(NaN, y))
// 0

六、数组实例的fill()

用法:fill()方法使用给定值,填充一个数组。

 var a,b,c;
 console.log(['a','b','c'].fill(8));		//[8,8,8]
//因此fill方法用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去。
  • fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c'],fill方法从 1 号位开始,向原数组填充 7,到 2 号位之前结束。

七、数组实例的entires(),keys(),values()

用法:用于遍历数组。keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

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"

八、数组实例的include()

用法:返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。包含返回true,不包含返回false。

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true
  • 该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。如果第二个数为正数 且超出数组长度,返回false。
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

九、数组实例的flat()、flatMap()

1、flat()

用法:flat()用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响。

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]
  • flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1。
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
  • 如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]
  • 如果原数组有空位,flat()方法会跳过空位。
[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]

2、flatMap()

1.用法:对原数组的每个成员执行Array.prototype.map(),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
  • flatMap()只能展开一层数组。
// 相当于 [[[2]], [[4]], [[6]], [[8]]].flat()
[1, 2, 3, 4].flatMap(x => [[x * 2]])
// [[2], [4], [6], [8]]
//遍历函数返回的是一个双层的数组,但是默认只能展开一层,因此flatMap()返回的还是一个嵌套数组。

十、数组的空位

1.定义:数组的某一个位置没有任何值。

Array(3) // [, , ,]
//Array(3)返回一个具有 3 个空位的数组。
  • 空位不是undefined,一个位置的值等于undefined,依然是有值的。空位是没有任何值。
  • ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位。

(1)forEach(), filter(), reduce(), every() 和some()都会跳过空位。
(2)map()会跳过空位,但会保留这个值
(3)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

Array.from方法会将数组的空位,转为undefined,也就是说,这个方法不会忽略空位。扩展运算符(…)也会将空位转为undefined。

Array.from(['a',,'b'])
// [ "a", undefined, "b" ]

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

十一、Array.prototype.sort()的排序稳定性

排序稳定性:是排序算法的重要属性,指的是排序关键字相同的项目,排序前后的顺序不变。

const arr = [
  'peach',
  'straw',
  'apple',
  'spork'
];

const stableSorting = (s1, s2) => {
    
    
  if (s1[0] < s2[0]) return -1;
  return 1;
};

arr.sort(stableSorting)
// ["apple", "peach", "straw", "spork"]
//排序结果是spork在straw前面,跟原始顺序相反,所以排序算法unstableSorting是不稳定的

猜你喜欢

转载自blog.csdn.net/ladream/article/details/109144643
今日推荐