假设我们有一个像这样的对象-
const obj = { name: "Ramesh", age: 34, occupation: "HR Manager", address: "Tilak Nagar, New Delhi", experience: 13 };
我们需要在对象上编写一个JavaScript函数,以计算它们的大小(即其中的属性数量)。
为此的代码将是-
const obj = { name: "Ramesh", age: 34, occupation: "HR Manager", address: "Tilak Nagar, New Delhi", experience: 13 }; Object.prototype.size = function(obj) { let size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)){ size++ }; }; return size; }; const size = Object.size(obj); console.log(size);
输出结果
控制台中的输出将为-
5