javascript 数组长度不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13541965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:06:07  来源:igfitidea点击:

Array length not working

javascriptmultidimensional-array

提问by Tudor Ravoiu

Possible Duplicate:
Array length undefined

可能重复:
数组长度未定义

I have the following array but whenever I try to find out the length with categoryData.lengthit gives me only undefined. If I type console.log(categoryData)it gives me all the objects in the array.

我有以下数组,但是每当我试图找出它的长度时,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"
        }
    ]
}

};

};

回答by raina77ow

That's because categoryData is not an Array - it's an Object. And while some JS objects (arguments, for example) support lengthproperty, those created with object literal notation do not.

那是因为 categoryData 不是数组 - 它是一个对象。虽然一些 JS 对象(arguments例如)支持length属性,但那些使用对象文字符号创建的对象不支持。

You can count your object's length by yourself, with this:

您可以自己计算对象的长度,如下所示:

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

This can be done even in a more simple way, if your target environment supports (or has it shimmed) the Object.keysmethod:

这甚至可以以更简单的方式完成,如果您的目标环境支持(或已填充)该Object.keys方法:

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

... and that's exactly how it's done in Underscore.js library method:

...这正是它在Underscore.js 库方法中的完成方式

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