[英]Destructuring all object properties without naming them individually
Destructuring an object: const p = {...this.props}
, I can access any property with p.propertyNameX
, p.propertyNameY
, etc.. const p = {...this.props}
对象: const p = {...this.props}
,我可以使用p.propertyNameX
、 p.propertyNameY
等访问任何属性。
I would prefer to simply use propertyNameX
and not use p.propertyNameX
.我宁愿简单地使用
propertyNameX
而不是使用p.propertyNameX
。
Can this be done without having to name all properties of the object like const {propertNameX, propertyNameY, etc...} = {...this.props}
?这是否可以在不必命名对象的所有属性的情况下完成,例如
const {propertNameX, propertyNameY, etc...} = {...this.props}
?
There is not really an option to just copy all your object fields to current scope variables without naming them separately.没有真正的选项可以将所有对象字段复制到当前范围变量而不单独命名它们。
But depending on what you want to achieve there are few other options.但是,根据您想要实现的目标,几乎没有其他选择。
I would strongly recommend you to refractor your code so you won't have to do that, but if it is some short, prototype code you can easily assign all object's properties to global like this:我强烈建议你折射你的代码,这样你就不必这样做了,但如果它是一些简短的原型代码,你可以轻松地将所有对象的属性分配给全局,如下所示:
for ( let prop in p ) {
global[prop] = p[prop];
}
after that, all of properties can be accesed just like a regular variable, so in your example you can now do之后,所有属性都可以像常规变量一样访问,因此在您的示例中,您现在可以执行
console.log(propertyNameX);
and property (now global variable) value will be displayed in console.和属性(现在是全局变量)值将显示在控制台中。
but keep in mind, this will not set this in your current scope, but as global application values , as side-effect overriding any of previous global variables and making them accessible everywhere.但请记住,这不会在您当前的范围内设置它,而是将其设置为全局应用程序值,作为覆盖任何先前全局变量并使它们在任何地方都可以访问的副作用。 Using global variables is an anty-pattern.
使用全局变量是一种反模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.