javascript 无法获取列表的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6251902/
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
Cannot get length of a list
提问by dotty
Hay, i have the following list
嘿,我有以下清单
var feedObjects = {
0:[
"url",
"image"
],
1:[
"url",
"image"
]
}
However when i try doing feedObjects.length it always returns null, any ideas?
但是,当我尝试执行 feedObjects.length 时,它总是返回 null,有什么想法吗?
回答by alex
You have an Object
({}
are the literal Object
notation), notan Array
, so there is no length
property.
你有一个Object
({}
有文字Object
符号),不是一个Array
,所以没有length
财产。
You will need to iterate over it with for ( in )
, except this guarantees no ordering of the properties, unlike an Array
(though in practice they generally come in the order defined).
您将需要使用 迭代它for ( in )
,除了这保证没有属性的排序,与 不同Array
(尽管实际上它们通常按定义的顺序出现)。
Better still, swap { }
with [ ]
and use a real Array
(well as close as JavaScript's arrays are to real ones).
更妙的是,换{ }
用[ ]
和使用一个真正的Array
(以及靠近JavaScript的数组是以假乱真)。
回答by Tim Rogers
You have declared an associative array, not an indexed array. Try this
您已声明关联数组,而不是索引数组。试试这个
var feedObjects = [
[
"url",
"image"
],
[
"url",
"image"
]
];
回答by kennebec
Your object doesn't have a length property or method-
您的对象没有长度属性或方法-
you need to count its members.
你需要计算它的成员。
var feedObjects={
["url","image"],["url","image"]
}
function count(){
var counter= 0;
for(var p in this){
if(this.hasOwnProperty(p))++counter;
}
return counter;
}
count.call(feedObjects)
returned value: (Number)=2
返回值:(Number)=2
or define an array:
或定义一个数组:
var feedObjects=[ ["url","image"],["url","image"]];
//feedObjects.length=2;
//feedObjects.length=2;
回答by FoRever_Zambia
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
alert(Object.size(feedObjects))