40

我正在研究这个动画功能,但我有一个问题。我似乎无法完成本应轻松的任务,我无法获得对象的长度。如果你查看那个 jsFiddle 你可以看到我正在运行alert(properties.length);并且它正在返回undefined。谁能明白为什么会这样?

4

5 回答 5

46

这在 node.js 和更新的环境中受支持。

var obj = {a: "a", b: "b"};
Object.keys(obj).length // 2
于 2012-03-06T17:58:27.260 回答
43

JavaScript 对象根本就没有属性length,只有Arrays做。如果您想知道在对象上定义的属性的数量,您必须遍历它们并计算它们。

此外,由于 in 的for in扩展,您的循环很容易出现错误,Object.prototype因为 in 将遍历完整的原型链并枚举链上的所有属性。

例子

// 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方法才能过滤掉那些不需要的属性。

// still the foo from above
for(var i in foo) {
    if (foo.hasOwnProperty(i)) {
        console.log(i); // only logs 'moo'
    }
}

许多 JavaScript 框架扩展了原型,不使用hasOwnProperty通常会导致可怕的错误。

更新

关于您的代码不是动画两个属性的实际问题。

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);
    }
    ....
 }
于 2011-01-14T11:31:25.190 回答
11

如果你使用Underscore.js,你可以使用_.size()

_.size({one : 1, two : 2, three : 3});
=> 3
于 2012-03-06T17:44:23.897 回答
0

对象没有长度,如果需要,您需要使用数组。

如果您必须找到对象中的属性数量,那么只有一种方法:

var length =0;
for(var i in obj) length++;
于 2011-01-14T11:30:51.257 回答
0

这是@Junaid Qadir Shekhanzai 的“查找对象长度”的一般功能(正如我们所说,应该正确地称为“计算对象的属性”)。它结合了@Ivo Wetzel 和@Martin Jespersen 的解决方案:

function countProperties(myObj){
    var length = 0;
    if(typeof myObj != 'object'){
        return false;
    }
    for(var i in myObj) {
    length++;
    }
    return length;
}
于 2017-10-31T21:49:00.250 回答