1、Object.assign()函数
Object.assign(target, source)
target为目标对象
source为源对象
该函数的作用是以目标对象为基础,将源对象中的内容更新到目标对象中,有则替换,无则新增
var result01 = {type: '01', name: 'ming', age: 23};
let result02 = {type: '02', marry: false};
let result03 = {type: '03', age: 55}
const result = Object.assign({}, result01, result02, result03);
DLog(result,result.name,result.type,result01);
结果

var result01 = {type: '01', name: 'ming', age: 23};
let result02 = {type: '02', marry: false};
let result03 = {type: '03', age: 55}
const result = Object.assign(result01, result02, result03);
DLog(result,result.name,result.type,result01);
结果

由此可以看出,如果不需要改变目标函数,第一个参数就置为空对象
2、...state函数
测试01:
let result01 = {type: '01', name: 'ming', age: 23};
console.log(result01);
console.log({...result01});
console.log({result01});
console.log([{...result01}]);
打印结果

说明 ...state 是把对象的元素拿出来作为一个新的集合
测试02:
let result01 = {type: '01', name: 'ming', age: 23};
let result02 = {type: '02', marry: false};
let result03 = {type: '03', age: 55,address:'beijing'}
const result = Object.assign({},result01, result02, result03);
console.log({...result02,...result03});
打印结果

测试03:
var arr0 = [0,1,2];
var arr1 = [3,4];
var arr3 = [arr0];
var arr4 = [...arr0];
console.log(arr3);
console.log(arr4);
打印结果

var arr0 = [0,1,2];
var arr1 = [3,4];
var arr3 = [arr0];
var arr4 = [...arr0,{...arr1}];
console.log(arr4);
打印结果

var arr0 = [0,1,2];
var arr1 = [3,4,0];
var arr3 = [arr0];
var arr4 = [...arr0,...arr1];
console.log(arr4);
打印结果

说明这是一个数据深拷贝的过程
把源对象的元素加入到目标函数中
对象合并
这样看...state与Object.assign()之间既有相似之处,也有各种特点
对比代码与结果,不难理解
网友评论