JavaScript 对象的长度 [英] Length of a JavaScript object

查看:21
本文介绍了JavaScript 对象的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScript 对象.是否有内置或公认的最佳实践方法来获取此对象的长度?

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

推荐答案

更新答案

这是 2016 年的更新和 ES5 的广泛部署 对于 IE9+ 和所有其他支持 ES5+ 的现代浏览器,您可以使用 Object.keys() 所以上面的代码就变成了:

Updated answer

Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

var size = Object.keys(myObj).length;

这不需要修改任何现有的原型,因为 Object.keys() 现在是内置的.

This doesn't have to modify any existing prototype since Object.keys() is now built-in.

编辑:对象可以具有无法通过 Object.key 方法返回的符号属性.因此,如果不提及它们,答案将是不完整的.

Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

符号类型已添加到语言中,以便为对象属性创建唯一标识符.Symbol 类型的主要好处是防止覆盖.

Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.

Object.keysObject.getOwnPropertyNames 不适用于符号属性.要返回它们,您需要使用 Object.getOwnPropertySymbols.

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

var person = {
  [Symbol('name')]: 'John Doe',
  [Symbol('age')]: 33,
  "occupation": "Programmer"
};

const propOwn = Object.getOwnPropertyNames(person);
console.log(propOwn.length); // 1

let propSymb = Object.getOwnPropertySymbols(person);
console.log(propSymb.length); // 2

最可靠的答案(即,在引起最少错误的同时捕捉您尝试做的事情的意图)是:

The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

Object.size = function(obj) {
  var size = 0,
    key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) size++;
  }
  return size;
};

// Get the size of an object
const myObj = {}
var size = Object.size(myObj);

JavaScript 中有一种约定,您不要向 Object.prototype 添加内容,因为它可以打破各种库中的枚举.不过,向 Object 添加方法通常是安全的.

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.

这篇关于JavaScript 对象的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆