JavaScript中的三个点(…)名叫扩展运算符,是在ES6中新增加的内容,它可以在函数调用/数组构造时,将数组表达式或者string在语法层面展开;还可以在构造字面量对象时将对象表达式按照key-value的方式展开
1,深拷贝一个对象
let obj = {name:’hello’, age:1};
let tmp = {…ogj}
tmp.name = ‘world’;
console.log(obj, ‘源对象’) ;
console.log(tmp, ‘复制的对象’) ;
打印:
Object {age:1, name:’hello’, __proto__:Object} “源对象”
Object {age:1, name:’world’, __proto__:Object} “复制的对象”
如上图所示,obj和tmp是完全两个独立的对象,互不影响
2.数组复制
let arr = [1,2,3]
let tmp = […arr]
tmp[2] = 0
console.log(arr, ‘源对象’) ;
console.log(tmp, ‘复制的对象’) ;
打印:
(3) [1, 2, 3] “源对象”
(3)[1, 0, 3] “复制的对象”
3.函数形参中使用
function func(name, …args) {
console.log(name);
console.log(args);
}
func(‘hello’, ‘a’, 1, 2, 3);
打印:
hello
(4) [‘a’, 1, 2, 3]
这里的…args,是对test函数中多余的参数进行收集,并转换成数组的形式进入函数体中
4.一种特殊情况,当数组里面套对象的时候,我们用[…]依然是无法深拷贝一份数据的,这个时候我们就要自己写递归函数了
let old = [{name:’hello’, age:1}]
let tmp = […old];
tmp[0].name = ‘world’;
console.log(old)
console.log(tmp)
打印:
Array(1)
0:{name:’hello’, age:1}
length:1
__proto__:Object
Array(1)
0:{name:’hello’, age:1}
length:1
__proto__:Object
Failed to load resource::ERR_FILE_NOT_FOUND
解决办法:自己写一个函数
function copySelf(obj) { var newobj = obj.constructor === Array ? [] : {}; if (typeof obj !=="object") { return; } for (var iin obj) { newobj[i] =typeof obj[i] ==="object" ? copySelf(obj[i]) : obj[i]; } return newobj; }
let old = [{name:’hello’, age:1}]
let tmp = copySelf(old);
tmp[0].name = ‘world’;
console.log(old)
console.log(tmp)
打印:
Array(1)
0:{name:’hello’, age:1}
length:1
__proto__:Object
Array(1)
0:{name:’world’, age:1}
length:1
__proto__:Object