Javascript Javascript获取对象中项目列表的长度?

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

Javascript Get length of list of items in object?

javascriptobjectcontent-length

提问by user3802348

I currently have a Javascript object that looks like this:

我目前有一个如下所示的 Javascript 对象:

Object {0: 8, 1: 9, 2: 10}

Object {0: 8, 1: 9, 2: 10}

I am trying to get the number of individual items in the object (i.e. 3) but can't figure out how to do so. Since the object isn't an array, I can't just call .length(). I tried huntsList[2].toString().split('.').lengthto split the items at the commas and count them in this way but it returns 1, since it converts the entire object to a single string that looks like this: ["[object Object]"].

我正在尝试获取对象中单个项目的数量(即 3),但不知道该怎么做。由于对象不是数组,我不能只调用.length(). 我试图huntsList[2].toString().split('.').length在逗号分割的项目,这样算来,但它返回1,因为它整个对象转换为一个字符串,看起来像这样:["[object Object]"]

Any suggestions for how I can accomplish this are appreciated.

任何关于我如何实现这一点的建议表示赞赏。

回答by omarjmh

You could get the keys using Object.keys, which returns an array of the keys:

您可以使用 获取键Object.keys,它返回一个键数组:

Example

例子

var obj = {0: 8, 1: 9, 2: 10};

var keys = Object.keys(obj);

var len = keys.length

回答by dork

You can use Object.keys(). It returns an array of the keys of an object.

您可以使用Object.keys(). 它返回一个对象键的数组。

var myObject = {0: 8, 1: 9, 2: 10};
console.log(Object.keys(myObject).length)

回答by TMB

1: ES5.1 solution use Object.keys - returns an array of a given object's own enumerable properties

1:ES5.1 解决方案使用 Object.keys - 返回给定对象自身可枚举属性的数组

var obj = {
  0: 8,
  1: 9,
  2: 10
}
console.log(Object.keys(obj).length)

2: Pre-ES5 Solution: use for..in and hasOwn

2:ES5 之前的解决方案:使用 for..in 和 hasOwn

var obj = {
  0: 8,
  1: 9,
  2: 10
};

var propsLength = 0;
for (prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    propsLength = propsLength + 1;
  }
}
console.log(propsLength);

3: Library Solution: Use lodash/underscore Convert it to an array, and query its length, if you need a pure js solution, we can look into how toArray works.

3:库解决方案:使用lodash/underscore将其转换为数组,并查询其长度,如果需要纯js的解决方案,我们可以看看toArray是如何工作的。

console.log(_.toArray({
  0: 8,
  1: 9,
  2: 10
}).length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>

回答by sudhakar phad

var obj = {0: 8, 1: 9, 2: 10};
alert(Object.keys(obj).length);

with this code, try to alert the length of you object mate.!

使用此代码,尝试提醒您对象的长度。!