在 Javascript 中声明空对象属性的简写,有吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6057214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shorthand to declaring empty object properties in Javascript, is there any?
提问by Edward
I need to declare a lot of object properties in my script and I wonder if the're any way to shorten this:
我需要在我的脚本中声明很多对象属性,我想知道是否有任何方法可以缩短它:
Core.registry.taskItemSelected;
Core.registry.taskItemSelected.id;
Core.registry.taskItemSelected.name;
Core.registry.taskItemSelected.parent;
Core.registry.taskItemSelected.summary;
Core.registry.taskItemSelected.description;
回答by Félix Saparelli
Wouldn't that work?
那不行吗?
Core.registry.taskItemSelected = {
id: null,
name: null,
parent: null,
...
};
回答by Shadow Wizard is Ear For You
Something like this should work:
这样的事情应该工作:
var props = ["id", "name", "parent", ...];
Core.registry.taskItemSelected = {};
for (var i = 0; i < props.length; i++)
Core.registry.taskItemSelected[props[i]] = "";
Edit: following the OP comments, here is better version with same final result:
编辑:按照 OP 评论,这里是具有相同最终结果的更好版本:
Object.prototype.declare = function (varArray) {
for (var i = 0; i < varArray.length; i++) {
this[varArray[i]] = {};
}
};
//usage:
var props = ["id", "name", "parent"];
Core = {};
Core.declare(props);
And live test case as well: http://jsfiddle.net/5fRDc/
还有实时测试用例:http: //jsfiddle.net/5fRDc/