Home > Article > Web Front-end > How does jQuery get and calculate the length of an object?
In our daily development, Objects are used very frequently. It is very convenient for us to calculate the length of the array, but how to calculate the length of the object? Suppose we have a library project with a set of books and authors, like the following:
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" };
We analyze the current needs and send data to an API, but the length of the book cannot exceed 100, So we need to calculate the total number of books in an object before sending the data. So what do we always do? We might do this:
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);
This is achievable, fortunately Javascript provides a changed method to calculate the length of the object:
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);
Below we To use the keys method on the array:
var arr = ["zuojj", "benjamin", "www.zuojj.com"]; //Outputs: ["0", "1", "2"] console.log(Object.keys(arr)); //Outputs: 3 console.log(arr.length);
Object.keys() method will return a property name consisting of all the enumerable own properties of the given object The array, the order of the attribute names in the array is consistent with the order returned when using a for-in loop to traverse the object (the main difference between the two is that for-in will also traverse an object from its prototype chainInherit to the enumerable properties).
Get the length of an object 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 ) );
The above is the detailed content of How does jQuery get and calculate the length of an object?. For more information, please follow other related articles on the PHP Chinese website!