美文网首页
我在JavaScript中用的较少的遍历

我在JavaScript中用的较少的遍历

作者: Guangchao | 来源:发表于2021-07-17 14:33 被阅读0次

JavaScript中对对象的遍历

1.for in遍历对象, 能够遍历出自身和继承的可枚举属性(Symbol除外);

function par(){

    this.parvar = 'pv';

}

var p = new par();

p.svar = 'sv';

for(var key in p){

    console.log(key,p[key]);

}

2. for of 遍历,ES6中介绍的新的遍历方法, 在ES6中引入了和java中类似的Iterator概念,实现了Iterator的对象,都支持 for of;

ES6 规定,默认的 Iterator 接口部署在数据结构的Symbol.iterator属性,或者说,一个数据结构只要具有Symbol.iterator属性,就可以认为是“可遍历的”(iterable)。Symbol.iterator属性本身是一个函数,就是当前数据结构默认的遍历器生成函数。执行这个函数,就会返回一个遍历器。

let obj = {

    data:['hello','world'],

    [Symbol.iterator](){

        const self = this;

        let index = 0;

        return {

            next();

            if(index <self.data.length){

                return{

                    value:self.data[index++],

                        done:false

                };

            }else{

                return {value:underfined , done:true};

            }

        }

    }

for(var key of obk){

    console.log(key,obj[key]);

    }

}

JavaScript中对数组的遍历

1.foreach方法

eg:

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

arr.forEach(function(value, index){

console.log('value=',value,'index=',index);

}

2.map遍历

3.for in

4.for of

相关文章

网友评论

      本文标题:我在JavaScript中用的较少的遍历

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