首頁  >  問答  >  主體

javascript - 在js中如何快速获取一个hash对象的键值对个数

比如我有一个对象

var obj = { 'aaa' : '111', 'bbb' : '222', 'ccc' : '333' };

类似这个样子,怎样获取它的键值对个数呢,如果是Array可以简单的用length获取,对object怎么获取呢?

大家讲道理大家讲道理2749 天前266

全部回覆(3)我來回復

  • 迷茫

    迷茫2017-04-10 14:49:11

    支持 ES5 的现代浏览器可以使用 Object.keys(obj).length,否则的话就没有简单的办法了。
    一个 polyfill:

    // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
    if (!Object.keys) {
      Object.keys = (function() {
        'use strict';
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
            dontEnums = [
              'toString',
              'toLocaleString',
              'valueOf',
              'hasOwnProperty',
              'isPrototypeOf',
              'propertyIsEnumerable',
              'constructor'
            ],
            dontEnumsLength = dontEnums.length;
    
        return function(obj) {
          if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
            throw new TypeError('Object.keys called on non-object');
          }
    
          var result = [], prop, i;
    
          for (prop in obj) {
            if (hasOwnProperty.call(obj, prop)) {
              result.push(prop);
            }
          }
    
          if (hasDontEnumBug) {
            for (i = 0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) {
                result.push(dontEnums[i]);
              }
            }
          }
          return result;
        };
      }());
    }
    

    Source

    回覆
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:49:11

    Object.keys(obj).length

    IE9+

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-10 14:49:11

    跨浏览器的话

    var arraySize = function(obj) {
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
    };
    
    var size = arraySize(yourArray);
    

    回覆
    0
  • 取消回覆