Object keys 与 for in 对比

2018-03-20  本文已影响0人  WilliamCha_8c18

for in一般用于遍历对象的属性;

作用于数组的for in除了会遍历数组元素外,还会遍历自定义可枚举的属性,以及原型链上可枚举的属性;

作用于数组的for in的遍历结果是数组的索引,且都为字符串型,不能用于运算;

某些情况下,可能按照随机顺序遍历数组元素;

Array.prototype.sayLength = function(){

  console.log(this.length);

  }

let arr = ['a','b','c','d'];

arr.name = '数组';

Object.defineProperties(arr,{

      type:{

                value:true,

                writable:true,

                enumerable:true

          }

    });

for(let i in arr){

    console.log(i);//0,1,2,3,name,type,sayLength

  }

Object.keys()

遍历结果为由对象自身可枚举属性组成的数组,数组中的属性名排列顺序与使用for in循环遍历该对象时返回的顺序一致;

与for in区别在于不能遍历出原型链上的属性;

Array.prototype.sayLength = function(){

            console.log(this.length);

        }

        let arr = ['a','b','c','d'];

        arr.name = '数组';

        Object.defineProperties(arr,{

            type:{

                value:true,

                writable:true,

                enumerable:true

            }

        });

var keys = Object.keys(arr);

console.log(keys);//["0", "1", "2", "3", "name", "type"]

上一篇 下一篇

猜你喜欢

热点阅读