Cho đối tượng:
const obj = {
name: "Ramesh",
age: 34,
occupation: "HR Manager",
address: "Tilak Nagar, New Delhi",
experience: 13
};
Yêu cầu: viết hàm trên prototype của Object để tính kích thước (số lượng thuộc tính riêng).
Mã thực hiện
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);
Kết quả
5