for...of数组遍历

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

   //给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 of str){
      console.log(i);//x,y,z
    };
    //数组
    for (let i of arr){
      console.log(i);//a,b,c
    };
    //对象
    for (let i of obj){
      console.log(i);//报错:obj is not iterable;(obj是不可迭代的)
    };

以上,for...of在遍历数组时会直接返回当前值

 

posted on 2020-05-31 18:23  loongw  阅读(595)  评论(0编辑  收藏  举报

导航