for...in根据key遍历
for...in区别:
遍历对象时会从原型上继承属性,可以用hasOwnProperty()识别出继承属性,
遍历数组会把数组下标看做属性名,也就输出结果是数组的下标,且不一定按照数组的索引顺序。
输出结果是字符串
function Person(name){ this.name = name; } Person.prototype.getName = function(){ return this.name; } var child= new Person('lala'); for (let i in child){ console.log(i); } //name //getName for (let i in child){ if(child.hasOwnProperty(i)){ console.log(i); } } //name var aa = ['aa','bb','cc']; for(let i in aa){ console.log(i); } // 0 1 2
for...of根据值遍历
for...of用来遍历数据,例如数组中的值,但是也可以遍历字符串,支持Map和Set对象的遍历,避免了所有for...in的弊端,与forEach相比可以正确响应break,continue,return语句。
var aa = ['aa','bb','cc']; for(let i of aa){ console.log(i); } // aa bb cc var str='abc'; for(let i of str){ console.log(i); } // a b c var set=new Set(['aa','bb','cc']); for(let i of set){ console.log(i); } //aa bb cc
forEach根据index遍历
forEach一般只能适用于数组,功能是从头到尾把数组遍历一遍,可以有三个参数,后两个可以不写
var arr = ['aa','bb']; arr.forEach(function(v,i,a){ console.log(v,i,a);//分别对应:数组元素,元素的索引,数组本身 }); //aa 0 ['aa','bb'] //bb 1 ['aa','bb']
讲真基础还是需要多练习,听说forEach是for循环的加强版,就想自己去实现下,结果想的有些复杂了还没做出来,于是百度了下,居然那么简单。
Array.prototype.eachFor = function(fn){ for(let i=0;i<this.length;i++){ fn(this[i],i,this); } } var aa=[5,6,7]; aa.eachFor(function(v,i){ console.log(v,i); }); //5 0 //6 1 //7 2
map根据index遍历
和forEach相比,使用方法一样有三个参数,map只能对元素进行加工处理,产生一个新的数组对象。
var arr=[1,2,3]; arr.map(function(v,i,arr){ return v*2; }); //[2,4,6] filter
filter对原数组进行过滤筛选,生成新的数组,使用和map样有三个参数。如果对空数组进行筛选,会返回undefined。filter不会改变原数组。
var aa=[1,2,1,2,3]; aa.filter(function(v,i,self){ return self.indexOf(v) == i; }); //[1,2,3]
for
for常规语句遍历,可循环数字,字符串,数组
for(let i=0;i<5;i++){ console.log(i); } //0 1 2 3 4