在我们日常开发中,对象的使用频率很高,我们计算数组的长度是非常方便的,但是如何计算对象的长度呢?
假如我们有一个图书馆的项目,项目中有一组图书和作者,像下面这样:
2 | "Farmer Giles of Ham" : "J.R.R. Tolkien" , |
3 | "Out of the Silent Planet" : "C.S. Lewis" , |
4 | "The Place of the Lion" : "Charles Williams" , |
5 | "Poetic Diction" : "Owen Barfield" |
我们分析现在的需求,我们给一个API发送数据,但是书的长度不能超过100,因此我们需要在发送数据之前计算在一个对象中总共有多少本书。那么我们总怎么做呢?我们可能会这样做:
01 | function countProperties (obj) { |
04 | for ( var property in obj) { |
05 | if (Object.prototype.hasOwnProperty.call(obj, property)) { |
13 | var bookCount = countProperties(bookAuthors); |
16 | console.log(bookCount); |
这是可以实现的,幸运的是Javascript提供了一个更改的方法来计算对象的长度:
02 | "Farmer Giles of Ham" : "J.R.R. Tolkien" , |
03 | "Out of the Silent Planet" : "C.S. Lewis" , |
04 | "The Place of the Lion" : "Charles Williams" , |
05 | "Poetic Diction" : "Owen Barfield" |
08 | var arr = Object.keys(bookAuthors); |
14 | console.log(arr.length); |
下面我们来对数组使用keys方法:
1 | var arr = [ "zuojj" , "benjamin" , "www.zuojj.com" ]; |
4 | console.log(Object.keys(arr)); |
7 | console.log(arr.length); |
Object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是 for-in 还会遍历出一个对象从其原型链上继承到的可枚举属性)。方法的兼容性及详情请戳这里。
Object.keys()方法,只能使用在现代浏览器,IE8及以下是不支持的,如果想支持IE低版本,可以使用es5-shim来兼容。其中代码如下:
05 | var hasDontEnumBug = !({ 'toString' : null }).propertyIsEnumerable( 'toString' ), |
06 | hasProtoEnumBug = ( function () {}).propertyIsEnumerable( 'prototype' ), |
13 | "propertyIsEnumerable" , |
16 | dontEnumsLength = dontEnums.length; |
18 | defineProperties(Object, { |
19 | keys: function keys(object) { |
20 | var isFn = isFunction(object), |
21 | isArgs = isArguments(object), |
22 | isObject = object !== null && typeof object === 'object' , |
23 | isStr = isObject && isString(object); |
25 | if (!isObject && !isFn && !isArgs) { |
26 | throw new TypeError( "Object.keys called on a non-object" ); |
30 | var skipProto = hasProtoEnumBug && isFn; |
32 | for ( var i = 0; i < object.length; ++i) { |
33 | theKeys.push(String(i)); |
36 | for ( var name in object) { |
37 | if (!(skipProto && name === 'prototype' ) && owns(object, name)) { |
38 | theKeys.push(String(name)); |
44 | var ctor = object.constructor, |
45 | skipConstructor = ctor && ctor.prototype === object; |
46 | for ( var j = 0; j < dontEnumsLength; j++) { |
47 | var dontEnum = dontEnums[j]; |
48 | if (!(skipConstructor && dontEnum === 'constructor' ) && owns(object, dontEnum)) { |
49 | theKeys.push(dontEnum); |
57 | var keysWorksWithArguments = Object.keys && ( function () { |
59 | return Object.keys(arguments).length === 2; |
61 | var originalKeys = Object.keys; |
62 | defineProperties(Object, { |
63 | keys: function keys(object) { |
64 | if (isArguments(object)) { |
65 | return originalKeys(ArrayPrototype.slice.call(object)); |
67 | return originalKeys(object); |
70 | }, !keysWorksWithArguments); |