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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:51:20  来源:igfitidea点击:

Object.length undefined in javascript

javascriptarraysobject

提问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.lengthreturns undefined. Fiddle is here.

coordinates.length返回未定义。 小提琴在这里

采纳答案by Alexander T.

That's because coordinatesis Objectnot Array, use for..in

这是因为,coordinatesObject不是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

coordinatesis an object. Objects in javascript do not, by default, have a lengthproperty. 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 keysin your object, which can be done via Object.keys():

您可能正在尝试查找keys对象中的数量,这可以通过Object.keys()以下方式完成:

var keyCount = Object.keys(coordinates).length;


Be careful, as a lengthproperty can be added to any object:

小心,因为length属性可以添加到任何对象:

var confusingObject = { length: 100 };

回答by AshBringer