数组长度不起作用

时间:2012-11-24 14:05:48

标签: javascript multidimensional-array

  

可能重复:
  Array length undefined

我有以下数组,但每当我尝试使用categoryData.length找出长度时,它只给我undefined。如果我输入console.log(categoryData),它会给我数组中的所有对象。

var categoryData = {
animals: {
    name: "Animals",
    description: "All your favorites from aardvarks to zebras.",
    items: [
        {
            name: "Pets"
        },
        {
            name: "Farm Animals"
        },
        {
            name: "Wild Animals"
        }
    ]
},
colors: {
    name: "Colors",
    description: "Fresh colors from the magic rainbow.",
    items: [
        {
            name: "Blue"
        },
        {
            name: "Green"
        },
        {
            name: "Orange"
        },
        {
            name: "Purple"
        },
        {
            name: "Red"
        },
        {
            name: "Yellow"
        },
        {
            name: "Violet"
        }
    ]
},
vehicles: {
    name: "Vehicles",
    description: "Everything from cars to planes.",
    items: [
        {
            name: "Cars"
        },
        {
            name: "Planes"
        },
        {
            name: "Construction"
        }
    ]
}

};

1 个答案:

答案 0 :(得分:8)

那是因为categoryData不是一个数组 - 它是一个对象。虽然某些JS对象(例如arguments)支持length属性,但使用对象文字表示法创建的对象则不支持。{/ p>

您可以自己计算对象的长度,用:

function countProps(obj) {
    var count = 0;
    for (var p in obj) {
      obj.hasOwnProperty(p) && count++;
    }
    return count; 
}

如果您的目标环境支持(或已经填充)Object.keys方法,即使以更简单的方式也可以这样做:

function sizeObj(obj) {
  return Object.keys(obj).length;
}

......而这正是Underscore.js library method中的完成方式:

_.size = function(obj) {
    if (obj == null) return 0;
    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};