美文网首页
for in 和for of

for in 和for of

作者: 爱吃西瓜的勺子 | 来源:发表于2020-08-17 15:22 被阅读0次

一、for in

for in 遍历的是数组的索引和对象的键名

  1. index是索引值,字符串形式,所以arr.index是undefined
  2. 遍历顺序可能不是按照书写顺序

Chrome Opera 中使用 for-in 语句遍历对象属性时会遵循一个规律,它们会先提取所有 key 的 parseFloat 值为非负整数的属性, 然后根据数字顺序对属性排序首先遍历出来,然后按照对象定义的顺序遍历余下的所有属性。其它浏览器则完全按照对象定义的顺序遍历属性。

3.for in 会遍历数组和对象中所有的可枚举属性,包括原型上的属性。

遍历数组

   Array.prototype.method=function(){
    console.log(this.length);
    }
    var arr=[1,2,4,5];
    arr.name='数组'
    for(let index in arr){
      console.log('index:'+index);
      console.log('arr[index]:'+arr[index]);
    }

image.png

遍历对象

   var obj={
      name:'ccdida',
      age:18,
      height:180,
      f:'ffff',
      '1':'1111'
    }

    for(let index in obj){
      console.log('index:'+index);
      console.log('arr[index]:'+obj[index]);
    }

image.png

二、for of

for...of语句在可迭代对象(包括ArrayMapSetStringTypedArrayarguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句

for of遍历的是数组每一个值

遍历数组

   Array.prototype.method=function(){
    console.log(this.length);
    }
    var arr=[1,2,4,5];
    arr.name='数组'
    for(let index of arr){
      console.log('index:'+index);

    }

image.png

遍历String

let iterable = "boo";

for (let value of iterable) {
  console.log(value);
}

image.png

for of 不可遍历对象

总结:

for in 适合遍历对象

for of适合遍历数组/字符串等可迭代对象

相关文章

网友评论

      本文标题:for in 和for of

      本文链接:https://www.haomeiwen.com/subject/nrjqjktx.html