数组中使用for循环
var a = [1,2,1,1,2,5,6,6,6,2,6,6,1,6];
for(let item of a){
console.log(item); //输出1,2,1,1,2 ...,
}
for( of )循环得到的是当前的值,而不是数组下标,如果循环到一个对象,那么你可以通过:item.属性 来对这个对象进行操作;
var a = [1,2,1,1,2,5,6,6,6,2,6,6,1,6];
for(let i in a){
console.log(item); //输出0,1,2,3 ...,
}
for( in )循环得到的是当前的数组下标;
对象中使用for循环
var b = {key1 : 1,key2: 2};
for(let i in b){
console.log(i); //输出key1,key2
}
for( in ) 循环得到的是该该键值对的key值;可以通过 key in b 来判断对象中是否存在该属性
var b = {key1: 1,key2: 2};
for(let i of b){
console.log(i); //输出b is not iterable
}
for( of ) 循环一个对象会报错;
使用for in/of得到数组中出现最多的元素
var a = [1,2,1,1,2,5,6,6,6,2,6,6,1,6];
var b = {};
for(let item of a){
if(item in b){
b[item]++;
}else{
b[item] = 1;
}
}
var max = 0;
for(let i in b){
max = b[i] > max ? b[i] : max;
}
for(let i in b){
if(b[i]==max){
console.log(i); //输出最多的元素
console.log(max); //输出次数
}
}