Object.length 在 JavaScript 中未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30861631/
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
Object.length undefined in javascript
提问by mpsbhat
I have an javascript object of arrays like,
我有一个数组的javascript对象,例如,
var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
but coordinates.length
returns undefined.
Fiddle is here.
但coordinates.length
返回未定义。
小提琴在这里。
采纳答案by Alexander T.
That's because coordinates
is Object
not Array
, use for..in
这是因为,coordinates
是Object
不是Array
,使用for..in
var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
for (var i in coordinates) {
console.log(coordinates[i])
}
or Object.keys
或者 Object.keys
var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
var keys = Object.keys(coordinates);
for (var i = 0, len = keys.length; i < len; i++) {
console.log(coordinates[keys[i]]);
}
回答by Armand
coordinates
is an object. Objects in javascript do not, by default, have a length
property. Some objects have a length property:
coordinates
是一个对象。默认情况下,javascript 中的对象没有length
属性。一些对象具有长度属性:
"a string - length is the number of characters".length
['an array', 'length is the number of elements'].length
(function(a, b) { "a function - length is the number of parameters" }).length
You are probably trying to find the number of keys
in your object, which can be done via Object.keys()
:
您可能正在尝试查找keys
对象中的数量,这可以通过Object.keys()
以下方式完成:
var keyCount = Object.keys(coordinates).length;
Be careful, as a length
property can be added to any object:
小心,因为length
属性可以添加到任何对象:
var confusingObject = { length: 100 };
回答by AshBringer
http://jsfiddle.net/3wzb7jen/2/
http://jsfiddle.net/3wzb7jen/2/
alert(Object.keys(coordinates).length);