es6中对象扩展运算符(三个点...)的简单运用
发布时间
阅读量:
阅读量
let Tarot = {
TheFool: "愚者",
TheMagician: 1,
TheLeangle: [1, 2, 3, 4, 5]
}
该扩展运算符的作用是获取所有参数对象可遍历的属性并复制到当前对象中。
let Marseilles = {...Tarot}
console.log(Marseilles);
//{
// "TheFool": "愚者",
// "TheMagician": 1,
// "TheLeangle": [1,2,3,4,5]
//}
在运算符扩展之后,
当引入与现有对象相同名称的TheLeangle作为参数时,
这将导致原有对象属性值的替换;
同时引入未曾拥有的TheEmpress这一参数时,
则会在目标对象中新增这一属性。
let Marseilles = { ...Tarot, TheLeangle: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], TheEmpress: "女皇" }
console.log(Marseilles);
//{
// "TheFool": "愚者",
// "TheMagician": 1,
// "TheLeangle": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
// "TheEmpress": "女皇"
//}
- 假设一个定义插件,默认插件配置宽100px,高200px
function plugin(params) {
let config = {
width: '100px',
height: '200px'
}
}
通过使用上面的方法,可以这样改变默认配置
function plugin(params) {
let config = {
width: '100px',
height: '200px'
}
config = { ...config, ...params }
console.log(config);
}
plugin(); // {width: "100px", height: "200px"}
plugin({width: '300px', height: '400px'}) // {width: "300px", height: "400px"}
- 因为数组是特殊的对象类型,在这种情况下对
象的扩展运算符同样适用于数组。
那么这样的好处是什么呢?通过查看输出内容可以看出,
这种设计使得将数组转换为对象更加便捷。
let arr = ['a', 'b', 'c'];
let foo = { ...arr };
console.log(foo); // {0: "a", 1: "b", 2: "c"}
【悰零笔记】
全部评论 (0)
还没有任何评论哟~
