Koc*_*r4d 14 javascript destructuring ecmascript-6 ecmascript-next
我有:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
Run Code Online (Sandbox Code Playgroud)
我可以用它来构造它:
const {gallery, select, ...other} = props
Run Code Online (Sandbox Code Playgroud)
我现在有三个变量:
[]() => null{one: 1,two: 2}是否有可能选择指定分组?
这样的事情(这不会起作用,但我希望看到我想要做的事情很清楚):
const {{gallery, select}: specific, ...other} = props
Run Code Online (Sandbox Code Playgroud)
所以我将有2个变量:
{gallery: [], select: () => null}{one: 1,two: 2}我可以在更高级别解决它并以这种方式构建道具:
const props = {
specific: {
gallery: [],
select: () => null,
},
other: {
one: 1,
two: 2,
}
}
Run Code Online (Sandbox Code Playgroud)
但我只是想知道这是否可能与解构.
那这个呢?others还包含specific数据,我必须首先访问props(也许这可以改进),但我认为它基本上是在解构时分组.它的工作原理是因为您可以在属性不存在时指定默认值:
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
console.log(specific);
console.log(others);Run Code Online (Sandbox Code Playgroud)
编辑
你也可以改变
const {gallery : gal, select : sel} = props;
const {specific: specific={gallery: gal, select: sel}, ...others} = props;
Run Code Online (Sandbox Code Playgroud)
有:
const {specific: specific={gallery: props.gallery, select: props.select}, ...others} = props;
Run Code Online (Sandbox Code Playgroud)
如果你想要它在一行.
此外,maioman的答案解决了我提到的others包含specific数据的问题,并没有直接访问道具.
将语法(和可读性)扩展到极限,您可以执行此操作:
(代码的解释在评论中)
const props = {
gallery: [],
select: () => null,
one: 1,
two: 2,
}
/** destructuring assignment **/
const {
gallery, //extract the gallery prop
select, //extract the select prop
specific: specific={gallery, select},
// create `specific` setting gallery and select props through default value assignment
...others // assign to others the rest of non extracted props properties
} = props;
console.log(specific);
console.log(others);Run Code Online (Sandbox Code Playgroud)
最后,我们在范围内获得了一个gallery和一个select对象,但我们已经成功地将它们作为新specific对象的属性.
使用警告:对象传播仍是提案
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |