ES6入门:关于新增扩展预算符(...)
一、扩展运算符(...)的作用:
扩展运算符 (spread) 是三个点 (...),用于取出参数对象中的所有可遍历的属性,浅拷贝到当前之中;
所以它的作用范围为 基础数据类型;
let test = [1, '2', '字符串', {a: 4, b: '5'}, [6, 7, 8]];
console.info(...test); // [1,"2","字符串",{"a":4,"b":"5"}, [6, 7, 8]]
let testCopy = [...test];
console.info(testCopy); // [1,"2","字符串",{"a":4,"b":"5"}, [6, 7, 8]]
// 更改属性值,对比,得出结论
testCopy[0] = 9; // 1 替换成 9
testCopy[2] = '修改后的值'; // '字符串' 替换成 '修改后的值'
testCopy[3].a = 10; // a 替换成 10
testCopy[3].b = '修改'; // '5' 替换成 修改
testCopy[4][0] = '11'; // 6 替换成 '11'
console.info(test); // [1,"2","字符串",{"a":10,"b":"修改"},["11",7,8]]
console.info(testCopy); // [9,"2","修改后的值",{"a":10,"b":"修改"},["11",7,8]]
结论:由最后打印的两个结果可知,对于 基础数据类型,在扩展拷贝的变量中修改对应值,不会影响到原本的变量中的存储值;对于 引用数据类型,在扩展拷贝的变量中修改对应值,会影响到原本变量中存储值;可以得出 扩展运算符 就是将遍历对象中的所有属性,浅拷贝到其中;
二、基本实现原理:
由上述可知,扩展运算符主要就是浅拷贝,可遍历对象属性;如果使用 ... ,那么可以使用 ES5 的写法实现:
function _spread() {
let arr = [];
for (let i = 0; i < arguments.length; i++) {
arr.concat(arguments[i]);
}
return arr;
};
let testArrs = [1, '2', '字符串', [3, 4, 5], {a:6, b:7}];
console.info(testArrs); // '[1, '2', '字符串', [3, 4, 5], {a:6, b:7}]'
let testCopyArrs = _spread(testArrs);
console.info(testArrs); // '[1, '2', '字符串', [3, 4, 5], {a:6, b:7}]'
三、常见用法:
1、浅拷贝数组和对象:
// 普通数组
let testArr = [1, '2', 3];
console.info(testArr); // [1, '2', 3]
console.info(...testArr); // 1 '2' 3 // 获取集合中所有的 value 值
let tempArr = [...testArr];
console.info(tempArr); // [1, '2', 3]
testArr[1] = '更改第二个元素的值';
// 对比打印后的值,得出结论
console.info(testArr); // [1, '更改第二个元素的值', 3]
console.info(tempArr); // [1, '2', 3]
// 普通对象
let testObj = {
a : '1',
b : '2',
};
console.info(testObj); // {a: '1', b: '2'}
console.info(...testObj); // Found non-callable @@iterator // 报错,无法打印,只能使用
let tempObj = {...testObj}; // {a: '1', b: '2'}
console.info(tempObj);
testObj.a = '变化后的值';
// 对比变化后的值,得出结论
console.info(testObj); // {a: '变化后的值', b: '2'}
console.info(tempObj); // {a: '1', b: '2'}
2、合并数据:
let testArr1 = [1, 2, 3];
let testArr2 = [4, 5, 6];
let testArr3 = [7, 8, 9];
// // ES5
testArr1.concat(testArr2, testArr3);
console.info(testArr1); // [1, 2, 3]
// ES6 合并数组
console.info([...testArr1, ...testArr2, ...testArr3]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
......
浙公网安备 33010602011771号