为什么 JSONObject.length 未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19032954/
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-09-03 19:50:23  来源:igfitidea点击:

Why is JSONObject.length undefined?

javascriptjson

提问by user2672420

In the code below, JSONObject.lengthis 2:

在下面的代码中,JSONObject.length是 2:

var JSONObject = [{
    "name": "John Johnson",
    "street": "Oslo West 16",
    "age": 33,
    "phone": "555 1234567"
}, {
    "name": "John Johnson",
    "street": "Oslo West 16",
    "age": 33,
    "phone": "555 1234567"
}];

However, in the code below, JSONObject.lengthis undefined. Why?

但是,在下面的代码中,JSONObject.length是未定义的。为什么?

var JSONObject = {
    "name": "John Johnson",
    "street": "Oslo West 16",
    "age": 33,
    "phone": "555 1234567"
};

回答by Doug

JavaScript doesn't have a .length property for objects. If you want to work it out, you have to manually iterate through the object.

JavaScript 没有对象的 .length 属性。如果你想解决这个问题,你必须手动遍历对象。

function objLength(obj){
  var i=0;
  for (var x in obj){
    if(obj.hasOwnProperty(x)){
      i++;
    }
  } 
  return i;
}


alert(objLength(JSONObject)); //returns 4

Edit:

编辑:

Javascript has moved on since this was originally written, IE8 is irrelevant enough that you should feel safe in using Object.keys(JSONObject).lengthinstead. Much cleaner.

自从最初编写 Javascript 以来,它已经发生了变化,IE8 已经无关紧要,您应该放心使用Object.keys(JSONObject).length。干净多了。

回答by Amol M Kulkarni

The following is actually an array of JSON objects :

以下实际上是一个 JSON 对象数组:

var JSONObject = [{ "name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"}, {"name":"John Johnson", "street":"Oslo West 16", 
"age":33, "phone":"555 1234567" }];

So, in JavaScript length is a property of an array. And in your second case i.e.

所以,在 JavaScript 中,长度是数组的一个属性。在你的第二种情况下,即

var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33, 
"phone":"555 1234567"};

the JSON object is not an array. So the length property is not available and will be undefined. So you can make it as an array as follows:

JSON 对象不是数组。因此 length 属性不可用且未定义。所以你可以把它做成一个数组,如下所示:

var JSONObject = [{"name":"John Johnson", "street":"Oslo West 16", "age":33, 
"phone":"555 1234567"}];

Or if you already have object say JSONObject. You can try following:

或者,如果您已经有对象 say JSONObject。您可以尝试以下操作:

var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33, 
"phone":"555 1234567"};
var jsonObjArray = []; // = new Array();
jsonObjArray.push(JSONObject);

And you do get lengthproperty.

而且你确实得到了length财产。