Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - JavaScript对象的长度(Length of a JavaScript object)

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

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

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
  ask by Gareth Simpson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The most robust answer (ie 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
var size = Object.size(myObj);

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.

(JavaScript中有一种约定,您不向Object.prototype添加内容 ,因为它可能会破坏各种库中的枚举。)

Adding methods to Object is usually safe, though.

(不过,向Object添加方法通常是安全的。)


Here's an update as of 2016 and widespread deployment of ES5 and beyond.

(这是2016年的更新,以及ES5及更高版本的广泛部署)

For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

(对于IE9 +和所有其他支持ES5 +的现代浏览器,可以使用Object.keys()因此上面的代码将变为:)

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

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

(由于现在已内置Object.keys()因此无需修改任何现有原型。)

Edit : Objects can have symbolic properties which can not be returned via Object.key method.

(编辑 :对象可以具有不能通过Object.key方法返回的符号属性。)

So the answer would be incomplete without mentioning them.

(因此,如果不提及它们,答案将是不完整的。)

Symbol type was added to the language to create unique identifiers for object properties.

(符号类型已添加到语言中,以创建对象属性的唯一标识符。)

Main benefit of Symbol type is prevention of overwrites.

(Symbol类型的主要好处是可以防止覆盖。)

Object.keys or Object.getOwnPropertyNames does not work for symbolic properties.

(Object.keysObject.getOwnPropertyNames不适用于符号属性。)

To return them you need to use Object.getOwnPropertySymbols .

(要返回它们,您需要使用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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...