假设我们有一个像这样的对象-
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