通过索引引用对象的属性是否安全?

发布于 2024-10-11 01:07:24 字数 342 浏览 2 评论 0原文

考虑一下,我有这个对象:

var ob = {
  "page1.html" : {...},
  "page2.html" : {...},
  "page3.html" : {...}
}

我无法将其更改为数组,我无权访问它,我想知道的是通过索引访问对象属性是否安全,所以:

var obVal = ob[0]; // reliably returns "page1.html"'s value every time

我知道在这种情况下不应该使用 for every 循环,因为值是散列的或其他什么?但是通过索引引用可能没问题吗?

Consider, I have this object:

var ob = {
  "page1.html" : {...},
  "page2.html" : {...},
  "page3.html" : {...}
}

I am unable to change this to an array, I don't have access to that, what I'd like to know is if it is safe to access the object properties by index, so:

var obVal = ob[0]; // reliably returns "page1.html"'s value every time

I know that a for each loop shouldn't be used in this situation because the values are hashed or something? But reference by index might be ok?

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

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

发布评论

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

评论(1

我们的影子 2024-10-18 01:07:24

不,ob[0] 甚至不起作用 - 它会给出undefined。事实上,如果您的对象是:

var ob = {
  "0": "blah",
  "page1.html" : {...},
  "page2.html" : {...},
  "page3.html" : {...}
}

ob[0] 将为您提供“blah”

for-each 循环适合这种情况的工具,但您应该检查循环中的每个索引是否实际上属于该对象,而不是属于父对象:

for (var i in ob) { // i will be "page1.html", "page2.html", etc...
    if (!ob.hasOwnProperty(i)) continue;
    // Do something with ob[i]
}

No, ob[0] won't even work - it will give undefined. In fact if your object was:

var ob = {
  "0": "blah",
  "page1.html" : {...},
  "page2.html" : {...},
  "page3.html" : {...}
}

ob[0] will give you "blah".

A for-each loop is the right tool for this situation, but you should just check that each index in the loop actually belongs to the object, and not to a parent:

for (var i in ob) { // i will be "page1.html", "page2.html", etc...
    if (!ob.hasOwnProperty(i)) continue;
    // Do something with ob[i]
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文