我想做这样的事情:
const vegetableColors = {corn: 'yellow', peas: 'green'};
const {*} = vegetableColors;
console.log(corn);// yellow
console.log(peas);// green
我似乎无法找到或弄清楚如何做到这一点,但我真的以为我以前见过它! :P
注意: 我在用着 巴别塔 同 stage
设置 0
;
背景: 我正试着变干 JSX 而不是参考 this.state
要么 this.props
到处。如果数据发生变化,也不必继续为destructure添加属性。
我想你正在寻找 with
声明,它完全符合您的要求:
const vegetableColors = {corn: 'yellow', peas: 'green'};
with (vegetableColors) {
console.log(corn);// yellow
console.log(peas);// green
}
但是,确实如此 弃用 (在严格模式下,包括ES6模块),有充分的理由。
将所有属性解构为当前范围
你不能在ES61。 这是一件好事。明确你要引入的变量:
const {corn, peas} = vegetableColors;
或者,您可以使用扩展全局对象 Object.assign(global, vegetableColors)
将它们放在全球范围内,但实际上,这比a更糟糕 with
声明。
1:......虽然我不知道在ES7中是否有草案允许这样的事情,但我可以告诉你任何提案都会被TC核实:-)
我想你正在寻找:
const {corn, peas} = vegetableColors;
生活在巴贝尔的REPL上
如果 Pointy是对的 你在问这个怎么做 无 知道名字 corn
和 peas
,你不能用解构赋值。
您只能在全局范围内使用循环,但我确定您不希望在全局范围内执行此操作。不过,以防万一:
// I'm sure you don't really want this, just being thorough
Object.keys(vegetableColors).forEach((key) => {
Object.defineProperty(this, key, {
value: vegetableColors[key]
});
});
(扔 enumerable: true
如果你想要这些伪常量可以枚举那么。)
这在全球范围内有效,因为 this
指全局对象。