To count the number of objects in object literal using Jquery

前端 未结 3 1728
旧巷少年郎
旧巷少年郎 2021-02-06 04:45

Code:

var animals = {
                    \"elephant\": {
                                    \"name\" : \"Bingo\",
                                    \"age\" :         


        
3条回答
  •  我寻月下人不归
    2021-02-06 05:26

    You could use Object.keys(animals).length

    Or

    var count = 0;
    for (var animal in animals) {
        if (animals.hasOwnProperty(animal)) {
            count++;
        }
    }
    // `count` now holds the number of object literals in the `animals` variable
    

    Or one of many jQuery solutions that may or may not be the most efficient:

    var count = $.map(animals, function(n, i) { return i; }).length;
    

提交回复
热议问题