Chinaunix首页 | 论坛 | 博客
  • 博客访问: 928143
  • 博文数量: 210
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2070
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-19 21:54
文章分类

全部博文(210)

文章存档

2020年(2)

2019年(18)

2018年(27)

2017年(5)

2016年(53)

2015年(88)

2014年(17)

分类: JavaScript

2018-08-28 10:15:55

ECMAScript将对象的属性分为两种:数据属性访问器属性。每一种属性内部都有一些特性,这里我们只关注对象属性的[[Enumerable]]特征,它表示是否通过 for-in 循环返回属性,也可以理解为:是否可枚举。

然后根据具体的上下文环境的不同,我们又可以将属性分为:原型属性实例属性。原型属性是定义在对象的原型(prototype)中的属性,而实例属性一方面来自己构造函数中,然后就是构造函数实例化后添加的新属性。

本文主要介绍JavaScript中获取对象属性常用到的三种方法的区别和适用场景。


for..in循环
使用for..in循环时,返回的是所有能够通过对象访问的、可枚举的属性,既包括存在于实例中的属性,也包括存在于原型中的实例。这里需要注意的是使用for-in返回的属性因各个浏览器厂商遵循的标准不一致导致对象属性遍历的顺序有可能不是当初构建时的顺序。

遍历数组

虽然for..in主要用于遍历对象的属性,但同样也可以用来遍历数组元素。

点击(此处)折叠或打开

  1. var arr = ['a', 'b', 'c', 'd'];

  2. // 使用for..in
  3. for (var i in arr) {
  4.   console.log('索引:' + i + ',值:' + arr[i]);
  5. }

  6. // 使用for循环
  7. for (var j = 0; j < arr.length; j++) {
  8.   console.log('索引:' + j + ',值:' + arr[j]);
  9. }

  10. /* 两种方式都输出:
  11.  * ----------------
  12.  * 索引:0,值:a
  13.  * 索引:1,值:b
  14.  * 索引:2,值:c
  15.  * 索引:3,值:d
  16.  * ----------------
  17.  */
如果扩展了原生的Array,那么扩展的属性为什么会被for..in输出? 这个问题也是上面我提到的两篇文章关注的重点。其实,这个问题如果我们将关注点放在for..in方法的定义上就不难看出端倪,定义中强调了一点它所遍历的是可枚举的属性。我们在扩展Array原型的时候有去对比自己添加的属性与Array原生的属性有什么不一样的地方吗?这里我强调的不一致的地方在于属性其中的一个特性[[enumberable]],在文章开头也有特意介绍了一下。如何查看一个属性的特性可以使用propertyIsEnumberable()Object.getOwnPropertyDescriptor()这两个方法。

点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. // 扩展Array.prototype
  3. Array.prototype.demo = function () {};

  4. for (var i in colors) {
  5.   console.log(i); // 输出: 0 1 2 demo
  6. }

  7. // 查看原生的方法[[enumberable]]特征,这里以splice为例
  8. Array.prototype.propertyIsEnumerable('splice'); // false
  9. Object.getOwnPropertyDescriptor(Array.prototype, 'splice'); // {writable: true, enumerable: false, configurable: true}

  10. // 查看 demo 属性的特性
  11. Array.prototype.propertyIsEnumerable('demo'); // true
  12. Object.getOwnPropertyDescriptor(Array.prototype, 'demo'); // {writable: true, enumerable: true, configurable: true}
从上面的示例代码中可以看出,我们添加的demo方法,默认是可以被for..in枚举出来的。如果想让其不被枚举,那么可以使用ES5的Object.defineProperty()来定义属性,此外如果浏览器版本不支持ES5的话,我们可以使用hasOwnProperty()方法在for..in代码块内将可枚举的属性过滤掉。

点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. Object.defineProperty(Array.prototype, 'demo', {
  3.   enumerable: false,
  4.   value: function() {}
  5. });

  6. Array.prototype.propertyIsEnumerable('demo'); // false
  7. Object.getOwnPropertyDescriptor(Array.prototype, 'demo'); // {writable: false, enumerable: false, configurable: false}

  8. for (var i in colors) {
  9.   console.log(i); // 输出:0 1 2
  10. }

  11. // 或者使用 hasOwnProperty
  12. var colors = ['red', 'green', 'blue'];
  13. Array.prototype.demo = function() {};

  14. // 安全使用hasOwnProperty方法
  15. var hasOwn = Object.prototype.hasOwnProperty;
  16. for (var i in colors) {
  17.   if (hasOwn.call(colors, i)) {
  18.     console.log(i); // 输出:0 1 2
  19.   }
  20. }
第二问题:for..in和for遍历数组时下标类型不一样 这里指的是for (var i in colors) {}for (var i = 0; i < colors.length; i++) {}中的i,示例如下:

点击(此处)折叠或打开

  1. ar colors = ['red', 'green', 'blue'];

  2. for (var i in colors) {
  3.   typeof i; // string
  4. }

  5. for (var j = 0; j < colors.length; j++) {
  6.   typoef i; // number
  7. }
至于为什么for..in在遍历数组时i为字符串?我的理解是如果我们从对象的视角来看待数组的话,实际上它是一个key为下标,value为数组元素值的对象,比如colors数组可以写成下面对象的形式:

点击(此处)折叠或打开

  1. var colors = {
  2.   0: 'red',
  3.   1: 'green',
  4.   2: 'blue'
  5. }

然后,我们需要访问colors对象中的属性,colors.0这样显然会报语法错识,那么只能使用colors['0']这种形式了。这可能就是为什么i的值为字符串,而不是数字的原因。

第三个问题:对于不存在的数组项的处理差异

最后一个问题在于数组中不存在元素的处理。对于数组来讲,我们知道如果将其length属性设置为大于数组项数的值,则新增的每一项都会取得undefined值。


点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. // 将数组长度变为10
  3. colors.length = 10;
  4. // 再添加一个元素的数组末尾
  5. colors.push('yellow');

  6. for (var i in colors) {
  7.   console.log(i); // 0 1 2 10
  8. }

  9. for (var j = 0; j < colors.length; j++) {
  10.   console.log(j); // 0 1 2 3 4 5 6 7 8 9 10
  11. }
示例中colors数组位置3到位置10项实际上都是不存在的。仔细观察使用for..in遍历数组的结果,我们发现对于不存在的项是不会被枚举出来的。通过chrome调式并监听colors变量,我们可以看到它的内部结构如下:

点击(此处)折叠或打开

  1. |----------------------|
  2. | colors |
  3. |----------------------|
  4. | 0 | 'red' |
  5. |----------------------|
  6. | 1 | 'green' |
  7. |----------------------|
  8. | 2 | 'blue' |
  9. |----------------------|
  10. | 10 | 'yellow' |
  11. |----------------------|
  12. | length | 11 |
  13. |----------------------|
  14. | __proto__ | Array[0] |
  15. |----------------------|
也就是说使用for..in遍历数组的结果实际上是和它在调试工具中看到的结构是一致的。虽然不存在的元素没有在调试工具中显示出来,但是它在内存中是存在的,我们仍然可以删除这些元素。

点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. colors.length = 10;
  3. colors.push('yellow');

  4. // 删除第4至第10项元素
  5. colors.splice(3, 6);

  6. for (var i in colors) {
  7.   console.log(i); // 输出:0 1 2 4
  8. }
虽然使用for..in遍历数组它自动过滤掉了不存在的元素,但是对于存在的元素且值为undefined或者'null'仍然会有效输出。此外我们也可以使用in操作符来判断某个key值(数组中的索引)是否存在对应的元素。

点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];

  2. 1 in colors; // true
  3. // 或者
  4. '1' in colors; // true

  5. // colors[3]没有对应的元素
  6. '3' in colors; // false

遍历对象

其实for..in操作的主要目的就是遍历对象的属性,如果只需要获取对象的实例属性,可以使用hasOwnProperty()进行过滤。


点击(此处)折叠或打开

  1. function Person(name, age) {
  2.   this.name = name;
  3.   this.age = age;
  4. }

  5. Person.prototype.getName = function() {
  6.   return this.name;
  7. }

  8. // 实例化
  9. var jenemy = new Person('jenemy', 25);

  10. for (var prop in Person) {
  11.   console.log(prop); // name age getName
  12. }

  13. var hasOwn = Object.prototype.hasOwnProperty;
  14. for (var prop2 in jenemy) {
  15.   if (hasOwn.call(jenemy, prop2)) {
  16.     console.log(prop2); // name age
  17.   }
  18. }

Object.keys()

Object.keys()用于获取对象自身所有的可枚举的属性值,但不包括原型中的属性,然后返回一个由属性名组成的数组。注意它同for..in一样不能保证属性按对象原来的顺序输出。



点击(此处)折叠或打开

  1. // 遍历数组
  2. var colors = ['red', 'green', 'blue'];
  3. colors.length = 10;
  4. colors.push('yellow');
  5. Array.prototype.demo = function () {};

  6. Object.keys(colors); // 0 1 2 10

  7. // 遍历对象
  8. function Person(name, age) {
  9.   this.name = name;
  10.   this.age = age;
  11. }

  12. Person.prototype.demo = function() {};

  13. var jenemy = new Person('jenemy', 25);

  14. Object.keys(jenemy); // name age
注意在 ES5 环境,如果传入的参数不是一个对象,而是一个字符串,那么它会报 TypeError。在 ES6 环境,如果传入的是一个非对象参数,内部会对参数作一次强制对象转换,如果转换不成功会抛出 TypeError。

点击(此处)折叠或打开

  1. / 在 ES5 环境
  2. Object.keys('foo'); // TypeError: "foo" is not an object

  3. // 在 ES6 环境
  4. Object.keys('foo'); // ["0", "1", "2"]

  5. // 传入 null 对象
  6. Object.keys(null); // Uncaught TypeError: Cannot convert undefined or null to object

  7. // 传入 undefined
  8. Object.keys(undefined); // Uncaught TypeError: Cannot convert undefined or null to object

由于Object.keys()为ES5上的方法,因此对于ES5以下的环境需要进行polyfill

点击(此处)折叠或打开

  1. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  2. if (!Object.keys) {
  3.   Object.keys = (function() {
  4.     'use strict';
  5.     var hasOwn = Object.prototype.hasOwnProperty,
  6.         hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
  7.         dontEnums = [
  8.           'toString',
  9.           'toLocaleString',
  10.           'valueOf',
  11.           'hasOwnProperty',
  12.           'isPrototypeOf',
  13.           'propertyIsEnumerable',
  14.           'constructor'
  15.         ],
  16.         dontEnumsLength = dontEnums.length;

  17.       return function(obj) {
  18.         if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  19.           throw new TypeError('Object.keys called on non-object');
  20.         }

  21.         var result = [], prop, i;

  22.         for (prop in obj) {
  23.           if (hasOwn.call(obj, prop)) {
  24.             result.push(prop);
  25.           }
  26.         }

  27.         if (hasDontEnumBug) {
  28.           for (i = 0; i < dontEnumsLength; i++) {
  29.             if (hasOwn.call(obj, dontEnums[i])) {
  30.               result.push(dontEnums[i]);
  31.             }
  32.           }
  33.         }
  34.         return result;
  35.       }
  36.   }) ();
  37. }

Object.getOwnPropertyNames()

Object.getOwnPropertyNames()方法返回对象的所有自身属性的属性名(包括不可枚举的属性)组成的数组,但不会获取原型链上的属性。


点击(此处)折叠或打开

  1. function A(a,aa) {
  2.   this.a = a;
  3.   this.aa = aa;
  4.   this.getA = function() {
  5.     return this.a;
  6.   }
  7. }
  8. // 原型方法
  9. A.prototype.aaa = function () {};

  10. var B = new A('b', 'bb');
  11. B.myMethodA = function() {};
  12. // 不可枚举方法
  13. Object.defineProperty(B, 'myMethodB', {
  14.   enumerable: false,
  15.   value: function() {}
  16. });

  17. Object.getOwnPropertyNames(B); // ["a", "aa", "getA", "myMethodA", "myMethodB"]

补充for..of

for..of为ES6新增的方法,主要来遍历可迭代的对象(包括Array, Map, Set, arguments等),它主要用来获取对象的属性值,而for..in主要获取对象的属性名。


点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. colors.length = 5;
  3. colors.push('yellow');

  4. for (var i in colors) {
  5.   console.log(colors[i]); // red green blue yellow
  6. }

  7. for (var j of colors) {
  8.   console.log(j); // red green blue undefined undefined yellow
  9. }

可以看到使用for..of可以输出包括数组中不存在的值在内的所有值。

其实除了使用for..of直接获取属性值外,我们也可以利用Array.prototype.forEach()来达到同样的目的。


点击(此处)折叠或打开

  1. var colors = ['red', 'green', 'blue'];
  2. colors.foo = 'hello';

  3. Object.keys(colors).forEach(function(elem, index) {
  4.   console.log(colors[elem]); // red green blue hello
  5.   console.log(colors[index]); // red green blue undefined
  6. });

  7. colors.forEach(function(elem, index) {
  8.   console.log(elem); // red green blue
  9.   console.log(index); // 0 1 2
  10. })

总结

其实这几个方法之间的差异主要在属性是否可可枚举,是来自原型,还是实例
方法 适用范围 描述
for..in 数组,对象 获取可枚举的实例和原型属性名
Object.keys() 数组,对象 返回可枚举的实例属性名组成的数组
Object.getPropertyNames() 数组,对象 返回除原型属性以外的所有属性(包括不可枚举的属性)名组成的数组
for..of 可迭代对象(Array, Map, Set, arguments等) 返回属性值











阅读(1667) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~