mps*_*hat 15 javascript arrays object
我有一个像数组的javascript对象,
var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
Run Code Online (Sandbox Code Playgroud)
但coordinates.length返回undefined.
小提琴就在这里.
Ale*_* T. 16
因为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])
}
Run Code Online (Sandbox Code Playgroud)
要么 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]]);
}
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/3wzb7jen/2/
alert(Object.keys(coordinates).length);
Run Code Online (Sandbox Code Playgroud)
coordinates是一个对象.默认情况下,javascript中的对象没有length属性.某些对象具有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
Run Code Online (Sandbox Code Playgroud)
您可能正在尝试查找keys对象中的数量,这可以通过Object.keys()以下方式完成:
var keyCount = Object.keys(coordinates).length;
Run Code Online (Sandbox Code Playgroud)
要小心,因为length属性可以添加到任何对象:
var confusingObject = { length: 100 };
Run Code Online (Sandbox Code Playgroud)