在 Javascript 中声明空对象属性的简写有吗?

发布于 2024-11-08 13:19:02 字数 293 浏览 0 评论 0原文

我需要在脚本中声明很多对象属性,我想知道是否有任何方法可以缩短它:

Core.registry.taskItemSelected;
Core.registry.taskItemSelected.id;
Core.registry.taskItemSelected.name;
Core.registry.taskItemSelected.parent;
Core.registry.taskItemSelected.summary;
Core.registry.taskItemSelected.description;

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

在风中等你 2024-11-15 13:19:02

那行不通?

Core.registry.taskItemSelected = {
  id: null,
  name: null,
  parent: null,
  ...
};

Wouldn't that work?

Core.registry.taskItemSelected = {
  id: null,
  name: null,
  parent: null,
  ...
};
铃予 2024-11-15 13:19:02

像这样的东西应该有效:

var props = ["id", "name", "parent", ...];
Core.registry.taskItemSelected = {};
for (var i = 0; i < props.length; i++)
   Core.registry.taskItemSelected[props[i]] = "";

编辑:按照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);

还有实时测试用例: http://jsfiddle.net/5fRDc/

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:

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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文