Javascript 计算Object的长度
获取数组长度比较简单
Var arr=[“as”,”da”];
arr.length不用加();
在我们日常开发中,对象的使用频率很高,我们计算数组的长度是非常方便的,但是如何计算对象的长度呢?
假如我们有一个图书馆的项目,项目中有一组图书和作者,像下面这样:
1var bookAuthors = { 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” 6};
我们分析现在的需求,我们给一个API发送数据,但是书的长度不能超过100,因此我们需要在发送数据之前计算在一个对象中总共有多少本书。那么我们总怎么做呢?我们可能会这样做:
01function countProperties (obj) { 02 varcount = 0; 03 04 for(var property in obj) { 05 if(Object.prototype.hasOwnProperty.call(obj, property)) { 06 count++; 07 } 08 } 09 10 returncount; 11} 12 13var bookCount = countProperties(bookAuthors); 14 15// Outputs: 4 16console.log(bookCount);
这是可以实现的,幸运的是Javascript提供了一个更改的方法来计算对象的长度:
01var bookAuthors = { 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” 06}; 07 08var arr = Object.keys(bookAuthors); 09 10//Outputs: Array [ “Farmer Giles of Ham”, “Out of the Silent Planet”, “The Place of the Lion”, “Poetic Diction” ] 11console.log(arr); 12 13//Outputs: 4 14console.log(arr.length);
下面我们来对数组使用keys方法:
1var arr = [“zuojj”,”benjamin”, “www.zuojj.com”]; 2 3//Outputs: [“0”, “1”, “2”] 4console.log(Object.keys(arr)); 5 6//Outputs: 3 7console.log(arr.length);
Object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,数组中属性名的排列顺序和使用for-in循环遍历该对象时返回的顺序一致(两者的主要区别是 for-in 还会遍历出一个对象从其原型链上继承到的可枚举属性)。方法的兼容性及详情请戳这里。
Object.keys()方法,只能使用在现代浏览器,IE8及以下是不支持的,如果想支持IE低版本,可以使用es5-shim来兼容。其中代码如下:
01// ES5 15.2.3.14 02// http://es5.github.com/#x15.2.3.14 03 04// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation 05var hasDontEnumBug = !({‘toString’:null}).propertyIsEnumerable(‘toString’), 06 hasProtoEnumBug = (function() {}).propertyIsEnumerable(‘prototype’), 07 dontEnums = [ 08 “toString”, 09 “toLocaleString”, 10 “valueOf”, 11 “hasOwnProperty”, 12 “isPrototypeOf”, 13 “propertyIsEnumerable”, 14 “constructor” 15 ], 16 dontEnumsLength = dontEnums.length; 17 18defineProperties(Object, { 19 keys:function keys(object) { 20 varisFn = isFunction(object), 21 isArgs = isArguments(object), 22 isObject = object !==null && typeof object === ‘object’, 23 isStr = isObject && isString(object); 24 25 if(!isObject && !isFn && !isArgs) { 26 thrownew TypeError(“Object.keys called on a non-object”); 27 } 28 29 vartheKeys = []; 30 varskipProto = hasProtoEnumBug && isFn; 31 if(isStr || isArgs) { 32 for(var i = 0; i < object.length; ++i) { 33 theKeys.push(String(i)); 34 } 35 }else { 36 for(var name in object) { 37 if(!(skipProto && name === ‘prototype’) && owns(object, name)) { 38 theKeys.push(String(name)); 39 } 40 } 41 } 42 43 if(hasDontEnumBug) { 44 varctor = object.constructor, 45 skipConstructor = ctor && ctor.prototype === object; 46 for(var j = 0; j < dontEnumsLength; j++) { 47 vardontEnum = dontEnums[j]; 48 if(!(skipConstructor && dontEnum === ‘constructor’) && owns(object, dontEnum)) { 49 theKeys.push(dontEnum); 50 } 51 } 52 } 53 returntheKeys; 54 } 55}); 56 57var keysWorksWithArguments = Object.keys && (function() { 58 // Safari 5.0 bug 59 returnObject.keys(arguments).length === 2; 60}(1, 2)); 61var originalKeys = Object.keys; 62defineProperties(Object, { 63 keys:function keys(object) { 64 if(isArguments(object)) { 65 returnoriginalKeys(ArrayPrototype.slice.call(object)); 66 }else { 67 returnoriginalKeys(object); 68 } 69 } 70}, !keysWorksWithArguments);