Javascript 计算Object的长度 - 起点终站

我们应该感谢相遇,无论结局是喜是悲....
Javascript 计算Object的长度
  • 首页 > IT技术
  • 作者:起点终站
  • 2017年7月5日 20:54 星期三
  • 浏览:14244
  • 字号:
  • 评论:0
  • 在我们日常开发中,对象的使用频率很高,我们计算数组的长度是非常方便的,但是如何计算对象的长度呢?
    假如我们有一个图书馆的项目,项目中有一组图书和作者,像下面这样:

    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 还会遍历出一个对象从其原型链上继承到的可枚举属性)。方法的兼容性及详情请戳这里

    Object.keys()方法,只能使用在现代浏览器,IE8及以下是不支持的,如果想支持IE低版本,可以使用es5-shim来兼容。其中代码如下:

    // ES5 15.2.3.14
    // http://es5.github.com/#x15.2.3.14
    
    // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
    var hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
        hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
        dontEnums = [
            "toString",
            "toLocaleString",
            "valueOf",
            "hasOwnProperty",
            "isPrototypeOf",
            "propertyIsEnumerable",
            "constructor"
        ],
        dontEnumsLength = dontEnums.length;
    
    defineProperties(Object, {
        keys: function keys(object) {
            var isFn = isFunction(object),
                isArgs = isArguments(object),
                isObject = object !== null && typeof object === 'object',
                isStr = isObject && isString(object);
    
            if (!isObject && !isFn && !isArgs) {
                throw new TypeError("Object.keys called on a non-object");
            }
    
            var theKeys = [];
            var skipProto = hasProtoEnumBug && isFn;
            if (isStr || isArgs) {
                for (var i = 0; i < object.length; ++i) {
                    theKeys.push(String(i));
                }
            } else {
                for (var name in object) {
                    if (!(skipProto && name === 'prototype') && owns(object, name)) {
                        theKeys.push(String(name));
                    }
                }
            }
    
            if (hasDontEnumBug) {
                var ctor = object.constructor,
                    skipConstructor = ctor && ctor.prototype === object;
                for (var j = 0; j < dontEnumsLength; j++) {
                    var dontEnum = dontEnums[j];
                    if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) {
                        theKeys.push(dontEnum);
                    }
                }
            }
            return theKeys;
        }
    });
    
    var keysWorksWithArguments = Object.keys && (function () {
        // Safari 5.0 bug
        return Object.keys(arguments).length === 2;
    }(1, 2));
    var originalKeys = Object.keys;
    defineProperties(Object, {
        keys: function keys(object) {
            if (isArguments(object)) {
                return originalKeys(ArrayPrototype.slice.call(object));
            } else {
                return originalKeys(object);
            }
        }
    }, !keysWorksWithArguments);
    

    如果此篇文章对你有帮助,请给个赞,文中不足之处,还望批评斧正!

    转自http://www.zuojj.com/archives/707.html

      您阅读这篇文章共花了:  
    本文作者:起点终站      文章标题: Javascript 计算Object的长度
    本文地址:https://blog.hellozwh.com/?post=303
    版权声明:若无注明,本文皆为“起点终站”原创,转载请保留文章出处。
    • blogger
    返回顶部| 首页| 手气不错| 网站地图| sitemap| 装逼生成器| 站长介绍|

    Copyright © 2016-2019 起点终站 闽ICP备16011094号-1