Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

JavaScript object literal 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?

question from:https://stackoverflow.com/questions/4690520/javascript-object-literal-length-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

Example

// Poisoning Object.prototype
Object.prototype.bar = 1;

var foo = {moo: 2};
for(var i in foo) {
    console.log(i); // logs both 'moo' AND 'bar'
}

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'
    }
}

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.

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);
    }
    ....
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...