JavaScript 对象字面量长度 === 未定义? [英] JavaScript object literal length === undefined?
问题描述
我正在研究这个动画功能,但我遇到了问题.我似乎无法执行应该是一项简单的任务,我无法获得对象的长度.如果您查看 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?
推荐答案
JavaScript 对象只是没有有length
属性,只有Arrays
做.如果你想知道一个对象上定义的属性的数量,你必须遍历它们并计算它们.
JavaScript object simply do not have a length
property, only Arrays
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.
此外,由于 Object.prototype
的扩展,您的 for in
循环容易出现错误,因为 in 将遍历完整的 原型链 并枚举所有链上的属性.
Also, your for in
loop is prone to bugs due extension of Object.prototype
since in will traverse the complete prototype chain and enumerate all the properties that are on the chain.
示例
// Poisoning Object.prototype
Object.prototype.bar = 1;
var foo = {moo: 2};
for(var i in foo) {
console.log(i); // logs both 'moo' AND 'bar'
}
您必须在对象上使用 hasOwnProperty 方法以过滤掉那些不需要的属性.
You have to use the hasOwnProperty method on the object in order to filter out those unwanted properties.
// still the foo from above
for(var i in foo) {
if (foo.hasOwnProperty(i)) {
console.log(i); // only logs 'moo'
}
}
许多 JavaScript 框架都扩展了原型,而不使用 hasOwnProperty
通常会导致可怕的错误.
Many JavaScript frameworks out there extend the prototype, not using hasOwnProperty
often leads to horrible bugs.
更新
关于您的代码不是动画这两个属性的实际问题.
Concerning the actual problem that your code is not animation both properties.
for(var p in properties) {
...
for(var i = 0; i <= frames; i++)
{
setTimeout((function(exti, element) {
return function() {
// p gets overriden by for outer for in loop
element.style[p] = original + (pixels * exti) + 'px';
}
// you need to pass in a copy of the value of p here
// just like you do with i and element
})(i, element), i * (1000 / 60), element);
}
....
}
这篇关于JavaScript 对象字面量长度 === 未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!