JavaScript对象文字长度=== undefined? [英] 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
property,仅 Arrays
do。如果你想知道在一个对象上定义的属性数,你必须迭代它们并计算它们。
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.
另外,你的 for
循环容易出现因 Object.prototype
的扩展而导致错误,因为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对象文字长度=== undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!