Home > Web Front-end > JS Tutorial > body text

How does jQuery get and calculate the length of an object?

伊谢尔伦
Release: 2017-06-17 13:26:04
Original
4153 people have browsed it

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"
};
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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 ) );
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template