【问题标题】:Dynamically creation of index for access of object propery动态创建索引以访问对象属性
【发布时间】:2013-06-13 20:18:37
【问题描述】:

我希望能够动态构建索引,以便可以使用按钮遍历对象属性。以下是我尝试过的,但不起作用。这是如何实现的?

var bodyNr = 3;
var theBody = {
    bodies: {
        1: null,
        2: null,
        3: null
    }
};
moveLeftBtn.on('click', function () {
    bodyNr -= 1;

    console.log(theBody.bodies["'" + bodyNr + "'"]); // undefined
    console.log(theBody.bodies['2']); // works
});

【问题讨论】:

  • FWIW,如果您需要索引,为什么不希望 theBody.bodies 成为一个数组?属性和索引是不同的,不应将其视为同一事物,即使您编写的作品也是如此。我不是骂人,只是提个建议。
  • 好点,改成数组了!

标签: javascript jquery object properties dynamically-generated


【解决方案1】:

你不需要撇号。

theBody.bodies[bodyNr]

应该可以。

【讨论】:

  • 该死,我之前尝试过但没有成功,现在当我做了一些其他更改并尝试了它时,它可以工作了。谢谢:)
【解决方案2】:

你不能只使用bodyNr 作为整数吗?

theBody.bodies[bodyNr] // null

另外,整数还有一个toString 方法

bodyNr.toString()

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2019-01-29
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多