在我们日常开发中,对象的使用频率很高,我们计算数组的长度是非常方便的,但是如何计算对象的长度呢?假如我们有一个图书馆的项目,项目中有一组图书和作者,像下面这样:
var bookauthors = {
"farmer giles of ham": "j.r.r. tolkien",
"out of the silent planet": "c.s. lewis",
"the place of the lion": "charles williams",
"poetic diction": "owen barfield"
};
我们分析现在的需求,我们给一个api发送数据,但是书的长度不能超过100,因此我们需要在发送数据之前计算在一个对象中总共有多少本书。那么我们总怎么做呢?我们可能会这样做:
function countproperties (obj) {
var count = 0;
for (var property in obj) {
if (object.prototype.hasownproperty.call(obj, property)) {
count++;
}
}
return count;
}
var bookcount = countproperties(bookauthors);
// outputs: 4
console.log(bookcount);
这是可以实现的,幸运的是javascript提供了一个更改的方法来计算对象的长度:
var bookauthors = {
"farmer giles of ham": "j.r.r. tolkien",
"out of the silent planet": "c.s. lewis",
"the place of the lion": "charles williams",
"poetic diction": "owen barfield"
};
var arr = object.keys(bookauthors);
//outputs: array [ "farmer giles of ham", "out of the silent planet", "the place of the lion", "poetic diction" ]
console.log(arr);
//outputs: 4
console.log(arr.length);
下面我们来对数组使用keys方法:
var arr = ["zuojj", "benjamin", "www.zuojj.com"];
//outputs: ["0", "1", "2"]
console.log(object.keys(arr));
//outputs: 3
console.log(arr.length);
object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是 for-in 还会遍历出一个对象从其原型链上继承到的可枚举属性)。
在 javascript 获取一个对象的长度实例:
/**
* jquery 扩展方法
*
* $.object.count( p )
* 获取一个对象的长度,需要指定上下文,通过 call/apply 调用
* 示例: $.object.count.call( obj, true );
* @param {p} 是否跳过 null / undefined / 空值
*
*/
$.extend({
// 获取对象的长度,需要指定上下文 this
object: {
count: function( p ) {
p = p || false;
return $.map( this, function(o) {
if( !p ) return o;
return true;
} ).length;
}
}
});
// 示例
// ---------------------------------------------------------------------------
var obj = {
a: null,
b: undefined,
c: 1,
d: 2,
e: 'test'
};
// 不过滤空值
console.log( $.object.count.call( obj ) );
// 过滤空值
console.log( $.object.count.call( obj, true ) );
以上就是jquery如何获取和计算对象的长度?的详细内容。