for...in对象遍历

for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性。

    //给Object和Array对象的原型添加两个属性
    Object.prototype.objCustom = function () { };
    Array.prototype.arrCustom = function () { };
    //定义要遍历的字符串、数组、对象
    const str="xyz";
    const arr=["a","b","c"];
    const obj={
          name: "tom",
          age: 18,
          hobby: "看电影"
    };
    //字符串
    for (let i in str){
      console.log(i);//0,1,2,objCustom            返回str字符串中每个字符的索引+Object对象原型的objCustom方法
    };
    //数组
    for (let i in arr){
      console.log(i);//0,1,2,arrCustom,objCustom  返回arr数组中每个值的索引+Array对象原型的arrCustom方法+Object对象原型的objCustom方法
    };
    //对象
    for (let i in obj){
      console.log(i);//name,age,hobby 返回属性名   返回obj对象中每个属性的属性名+Object对象原型的objCustom方法
    };

以上,for...in在遍历数组时,不仅遍历了数组中的索引,还会遍历其他可枚举属性;

显然,当我们只想取数组中的值时,它干了多余的事

for...in是为遍历对象属性而构建的;虽然对数组有效,但不推荐这么做

原文地址:https://www.cnblogs.com/vinson-blog/p/13020035.html