指的是键的数量。
function objectSize(the_object) {
/* function to validate the existence of each key in the object to get the number of valid keys. */
var object_size = 0;
for (key in the_object){
if (the_object.hasOwnProperty(key)) {
object_size++;
}
}
return object_size;
}
用法
// Arbitrary object
var something = {
dog: "cat",
cat: "dog"
}
console.log(objectSize(something));
// Logs: 2
确保在循环中在key前面添加var
for (var key in the_object){
这样变量key就会在函数作用域内失效。
在调试IE代码时偶然发现了这篇文章。IE 9之前的版本似乎在直接对对象使用Object.keys和.hasOwnProperty时存在问题。因此需要更复杂的替代方案,可以在此处找到
http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
希望对您有所帮助。
我喜欢这个Chris,但将其添加到Object原型中似乎更正确。IE
Object.prototype.size = function() {
var size = 0
// 您的代码,但使用“this”
return size;
}
使用something.size()调用
据我了解,向对象原型添加新函数应该没问题。
嘿,Sam,你能写出你的建议吗?我对这一点有点困惑。
感谢您的帮助。