ES6扩展运算符三个点(...)详解

99 篇文章 12 订阅
18 篇文章 0 订阅

对象的扩展运算符:

对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中

let fx = {a: 1, b: 2};
let fxs = {...fx};
console.log(fxs) // {a: 1, b: 2}

等价于

let fx = {a: 1, b: 2};
let fxs = Object.assign({}, fx)
console.log(fxs) // {a: 1, b: 2}

同样,如果用户自定义的属性,放在扩展运算符后面,则扩展运算符内部的同名属性会被覆盖掉。

let fx = {a: 1, b: 2};
let fxs = {...fx, a:3, ...{b:3, c:2}};
console.log(fxs) // {a: 3, b: 3, c: 2}

扩展运算符对对象实例的拷贝属于一种浅拷贝(拷贝的时候拷贝的是对象的引用)。

let fx = {a: 1, b: 2, c: {age: 18}};
let fxs = {...fx};
console.log(fxs) // {a: 3, b: 3, c: {age: 18}}

==================

fx.c.age = 8
console.log(fx) // {a: 3, b: 3, c: {age: 8}}
console.log(fxs) // {a: 3, b: 3, c: {age: 8}}

数组的扩展运算符

  • 可以将数组转换为参数序列
function add(x, y) {
  return x + y;
}

const numbers = [4, 38];
add(...numbers) // 42
  • 可以复制数组
const arr1 = [1, 2];
const arr2 = [...arr1];
console.log(arr2) // [1, 2]
  • 扩展运算符可以与解构赋值结合起来,用于生成数组(如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错)
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first) // 1
console.log(rest)  // [2, 3, 4, 5]

============

// 错误的写法
const [...rest, first] = [1, 2, 3, 4, 5];
console.log(first) // Rest element must be last element
console.log(rest)  
  • 扩展运算符还可以将字符串转为真正的数组
[...'fx'] // ["f", "x"]
  • 任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组
function foo() {
    console.log(arguments) // [1, 2, 3, callee: function, Symbol(Symbol.iterator): function]
    const args = [...arguments];
    console.log(args) // [1, 2, 3]
}
foo(1, 2, 3) 

输出如下,可以看出arguments不是一个数组,而是一个伪数组,使用扩展运算符可以将其转换成真数组

但是扩展运算符不能把没有迭代器iterator的伪数组转为数组

let likeArr = { "0":1,"1":2,"length":2 }
let arr = [...likeArr] // 报错 TypeError: object is not iterable

// 但是可以用Array.from把伪数组转为数组
let likeArr = { "0":1,"1":2,"length":2 }
let arr = Array.from(likeArr)
console.log(arr) // [1,2]

等价于apply的方式:如果想将数组元素迭代为函数参数,一般使用Function.prototype.apply 的方式进行调用。

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);

==========

function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);

所有参数都可以通过展开语法来传值,也不限制多次使用展开语法。

function myFunction(v, w, x, y, z) { 
	console.log(...arguments) // -1 0 1 2 3
}
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wflynn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值