总结:遍历数组使用of,遍历{a:”aaa”,b:”bbb”}对象使用in
in表示指定对象中含有指定属性名
var arr = ['a','b','c','d'];
1 in arr //true
'length' in arr //true
var obj = {a:'aaa', b:'ddd', c:undefined};
delete = obj.b;
'a' in obj //true
'b' in obj //false
'c' in obj //true
'toString' in obj //true
对于数组而言属性名为1,2,3…
对于delete后的属性名,返回false
对于继承原型链上的属性,返回true
for in
会遍历指定对象上所有属性名
var a = [1,2,3];
for(var key in a){
if(a.hasOwnProperty(key)){
console.log(key);
}
}//1,2,3
for(var key in a){
console.log(key);
}//1,2,3,has
var man ={hands:2,legs:2,heads:1};
//为所有的对象添加clone方法,即给内置原型(object,Array,function)增加原型属性,该方法很强大,也很危险
if(typeof Object.prototype.clone ==="undefined"){
Object.prototype.clone = function(){};
}
//
for(var i in man){
if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性
console.log(i,":",man[i]);
};
}
//输出结果为print hands:2,legs:2,heads:1
for(var i in man) {//不使用过滤
console.log(i,":",man[i]);
} //输出结果hands : 2,legs : 2 ,heads : 1 ,clone : function (){}
for(var i in man) {
if(Object.prototype.hasOwnProperty.call(man,i)) { //过滤
console.log(i,":",man[i]);
}
}
//输出结果为print hands:2,legs:2,heads:1
for of
遍历Array,Map,Set,String,TypedArray,arguments 对象等等,不能遍历{a:”aaa”,b:”bbb”}类型
var a = [1,2,3,4];
for(var key of a){
console.log(key);
}//1,2,3,4
for(var key of a){
key +=1;
console.log(key);
}//2,3,4,5