Object.length undefined in javascript
This question already has an answer here:
That because coordinates
is Object
not Array
, use 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
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]]);
}
coordinates
is an object. Objects in javascript do not, by default, have a length
property. Some objects have a length property:
"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()
:
var keyCount = Object.keys(coordinates).length;
Be careful, as a length
property can be added to any object:
var confusingObject = { length: 100 };
http://jsfiddle.net/3wzb7jen/2/
alert(Object.keys(coordinates).length);
链接地址: http://www.djcxy.com/p/27260.html
上一篇: 如何找到JSON对象的长度