通过索引引用对象的属性是否安全?
考虑一下,我有这个对象:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,
ob[0]
甚至不起作用 - 它会给出undefined
。事实上,如果您的对象是:ob[0]
将为您提供“blah”
。for-each 循环是适合这种情况的工具,但您应该检查循环中的每个索引是否实际上属于该对象,而不是属于父对象:
No,
ob[0]
won't even work - it will giveundefined
. In fact if your object was: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: