JavaScript 对象字面量长度 === 未定义?
我正在研究这个动画功能,但我有一个问题。我似乎无法执行应该是一项简单的任务,我无法获得对象的长度。如果您检查 jsFiddle,您可以看到我正在运行 alert(properties.length);
并且它返回 undefined
。谁能明白为什么会这样吗?
I am working on this animation function but I have a problem. I can't seem to perform what should be an easy task, I can not get the length of an object. If you check out that jsFiddle you can see that I am running alert(properties.length);
and it is returning undefined
. Can anyone see why this might be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这在 Node.js 和较新的环境中受支持。
This is supported in node.js and newer environments.
JavaScript 对象不没有
length
属性,只有Arrays
有。如果您想知道对象上定义的属性数量,则必须迭代它们并对它们进行计数。此外,由于
Object.prototype
的扩展,您的for in
循环很容易出现错误,因为 in 将遍历完整的原型链并枚举链上的所有属性。示例
您必须使用hasOwnProperty 对象上的方法以过滤掉那些不需要的属性。
许多 JavaScript 框架都扩展了原型,不使用
hasOwnProperty
通常会导致可怕的错误。更新
关于您的代码不是动画这两个属性的实际问题。
JavaScript object simply do not have a
length
property, onlyArrays
do. If you want to know the number of properties that are defined on a object, you have to iterate over them and count them.Also, your
for in
loop is prone to bugs due extension ofObject.prototype
since in will traverse the complete prototype chain and enumerate all the properties that are on the chain.Example
You have to use the hasOwnProperty method on the object in order to filter out those unwanted properties.
Many JavaScript frameworks out there extend the prototype, not using
hasOwnProperty
often leads to horrible bugs.Update
Concerning the actual problem that your code is not animation both properties.
如果您使用 Underscore.js,则可以使用
_.size()
:If you are using Underscore.js, you can use
_.size()
:对象没有长度,如果需要,您需要使用数组。
如果您必须查找对象中属性的数量,只有一种方法:
Objects have no length, you'll need to use an array if you want that.
If you have to find the number of properties in an object there is only one way:
这是@Junaid Qadir Shekhanzai 的“查找对象的长度”的通用函数(正如我们所说,应该正确地称为“计算对象的属性”)。它结合了 @Ivo Wetzel 和 @Martin Jespersen 的解决方案:
Here's @Junaid Qadir Shekhanzai's general function for "finding the length of an object" (which as we're told, should properly be called "counting the properties of an object"). It combines solutions from @Ivo Wetzel and @Martin Jespersen: