ES6中数组新增了哪些扩展?


一、扩展运算符的应用

ES6通过扩展元素符…,好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列

console.log(...[1, 2, 3])// 1 2 3
console.log([...[1, 2, 3]]) //[1,2,3]
console.log(1, ...[2, 3, 4], 5)// 1 2 3 4 5
[...document.querySelectorAll('div')]// [<div>, <div>, <div>]

也可以实现数组的复制和合并

复制:

const a1 = [1, 2];
const [...a2] = a1;
console.log(a2);//[1,2]

注意:通过扩展运算符实现的是浅拷贝,修改了引用指向的值,会同步反映到新数组

合并:

const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
console.log([...arr1, ...arr2, ...arr3]);//['a', 'b', 'c', 'd', 'e']

扩展运算符可以与解构赋值结合起来,用于生成数组

例如:

const [one,two, ...rest] = [1, 2, 3, 4, 5];
console.log(one); // 1
console.log(two); //2
console.log(rest);  // [3, 4, 5]

const [one, ...rest] = [];
console.log(one); // undefined
console.log(rest);  // []

const [one, ...rest] = ["foo"];
console.log(one);  // "foo"
console.log(rest);   // []

如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错

const [...butLast, last] = [1, 2, 3, 4, 5];
// 报错

const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 报错

可以将字符串转为真正的数组

const a  = [...'hello']
console.log(a);//['h', 'e', 'l', 'l', 'o']

定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组

let map = new Map([
    [1, 'one'],
    [2, 'two'],
    [3, 'three'],
]);
console.log(map);//Map(3) {1 => 'one', 2 => 'two', 3 => 'three'}
let arr1 = [...map.keys()]; 
let arr2 = [...map.values()]; 
console.log(arr1);// [1, 2, 3]
console.log(arr2);// ['one', 'two', 'three']

如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错

const obj = {a: 1, b: 2};
let arr = [...obj]; // TypeError: Cannot spread non-iterable object

二、构造函数新增的方法

关于构造函数,数组新增的方法有如下:

  • Array.from()
  • Array.of()

Array.from()

会把一个类数组或对象,转成真正的数组,但是这个类数组必须具有length属性

var list={
    0:"韩信",
    1:"李白",
    2:"诸葛亮",
    3:"赵云",
    length:4
}
var arr = Array.from(list)
console.log(arr);//["韩信", "李白", "诸葛亮", "赵云"]

字符串拆分为数组

console.log(Array.from('matt'))//['m','a','t','t'];

将两类对象转为真正的数组:类似数组的对象和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

const s = new Map().set(1,2).set(3,4);
const a = new Set().add(1).add(2).add(3);
console.log(Array.from(s)) // [[1,2],[3,4]]
console.log(Array.from(a)) // [1,2,3];

arguments 可以轻松转换为数组

function getArr() {
    console.log(arguments);//Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    return Array.from(arguments);
}
console.log(getArr(1, 2, 3, 4)) //[1, 2, 3, 4]

对现有的数组进行浅复制

 const a1 = [1,2,3,4];
 const b1 = Array.from(a1);
 console.log(b1)//[1,2,3,4];
 console.log(a1 === b1) //false

还可以接受第二个参数,用来对每个元素进行处理,将处理后的值放入返回的数组

const arr = Array.from([1, 2, 3], (x) => {
    console.log(x);//1,2,3
    return x
})
console.log(arr);//[1,2,3]

Array.of()

用于将一组值,转换为数组

var arr = Array.of(1,2,3,4)
console.log(arr);// [1, 2, 3, 4]

没有参数的时候,返回一个空数组
当参数只有一个的时候,实际上是指定数组的长度
参数个数不少于 2 个时,Array()才会返回由参数组成的新数组

Array() // []空数组
Array(3) // [, , ,]长度为3的空数组
Array(3, 11, 8) // [3, 11, 8]

Array.of()和Array()的区别

Array(7)表示创建了一个长度为7的空数组;
Array.of(7)表示创建了一个数组里面有单个元素7的数组,它的长度为1。

例如:

let arr1 = Array(10)
console.log(arr1); // [empty × 10] 是一个长度为10的空数组
let arr2 = Array.of(10)
console.log(arr2); // [10] 是一个有单个元素10的数组,它的长度为1

三、实例对象新增的方法

关于数组实例对象新增的方法有如下:

  • copyWithin()
  • find()、findIndex()
  • fill()
  • entries(),keys(),values()
  • includes()
  • flat(),flatMap()

copyWithin()

将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组 参数如下:

arr.copyWithin(target, start, end)

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

let arr = [1, 2, 3, 4, 5].copyWithin(0, 3)// 将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2
console.log(arr);//[4, 5, 3, 4, 5] 

let arr = [1, 2, 3, 4, 5].copyWithin(0, 3, 4)// 将从 3 号位直到4号位结束的成员4,复制到从 0 号位开始的位置,结果覆盖了原来的 1
console.log(arr);//[4, 2, 3, 4, 5]

find()、findIndex()

find()用于找出第一个符合条件的数组成员

参数是一个回调函数,接受三个参数依次为当前的值、当前的位置和原数组

let arr = [1, 5, 10, 15].find(function (value, index, arr) {
    return value > 9;
})
console.log(arr); // 10

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

let arr = [1, 5, 10, 15].findIndex(function (value, index, arr) {
    return value > 9;
})
console.log(arr); // 2

fill()

使用给定值,填充一个数组

let arr1 = ['a', 'b', 'c'].fill(7)
console.log(arr1);// [7, 7, 7]

let arr2 = new Array(3).fill(7)
console.log(arr2);// [7, 7, 7]

还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置

let arr =['a', 'b', 'c'].fill(7, 1, 2)
console.log(arr); // ['a', 7, 'c']

entries(),keys(),values()

keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历

for (let index of ['a', 'b'].keys()) {
    console.log(index);
    //0
    //1
}

for (let index of ['a', 'b'].values()) {
    console.log(index);
    //a
    //b
}

for (let index of ['a', 'b'].entries()) {
    console.log(index);
    //[0, 'a']
    //[1, 'b']
}

includes()

用于判断数组是否包含给定的值

let arr1 = [1, 2, 3].includes(2)     
console.log(arr1);// true
let arr2 = [1, 2, 3].includes(4)     
console.log(arr2);// false
let arr3 = [1, 2, NaN].includes(NaN) 
console.log(arr3);// true

方法的第二个参数表示搜索的起始位置,默认为0
参数为负数则表示倒数的位置

let arr1 = [1, 2, 3, 4, 5, 6].includes(3,3);
console.log(arr1);// false
let arr2 = [1, 2, 3].includes(3, -1);
console.log(arr2);// true

flat(),flatMap()

将数组扁平化处理,返回一个新数组,对原数据没有影响

let arr = [1, 2, [3, 4]].flat()
console.log(arr); // [1, 2, 3, 4]

flat()默认只会“拉平”一层,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数,默认为1

let arr1 = [1, 2, [3, [4, 5]]].flat()
console.log(arr1);// [1, 2, 3, [4, 5]]

let arr2 = [1, 2, [3, [4, 5]]].flat(2)
console.log(arr2);// [1, 2, 3, 4, 5]

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

var arr = [2, 3, 4].flatMap((x) =>{
     console.log(x);
     //2
     //3
     //4
     return [x, x * 2]
 })
 console.log(arr);// [2, 4, 3, 6, 4, 8]

四、数组的空位

数组的空位指,数组的某一个位置没有任何值
ES6则是明确将空位转为undefined,包括Array.from、扩展运算符、copyWithin()、fill()、entries()、keys()、values()、find()和findIndex()
建议大家在日常书写中,避免出现空位

五、排序稳定性

将sort()默认设置为稳定的排序算法,如果是字符串就按26个英文字母排序

const arr = [
    'peach',
    'straw',
    'apple',
    'spork'
];
arr.sort()
console.log(arr); // ["apple", "peach", "straw", "spork"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值