1.原生循环
// -----1 for 循环
for(var i=0;i<n;i++){
console.log(i) //输出为 1,2,3,4…
}
// -----2 JavaScript 的for-in循环,只能获得对象的key,不能直接获取value
var arr={'1':'a','2':'b','3':'c','4':'d'};
for(let i in arr){
console.log(i) //输出为 1,2,3,4
}
// -----3 ES6 for-of循环,可直接获取value
var arr={'1':'a','2':'b','3':'c','4':'d'};
for(let i of arr){
console.log(i) //输出为 a,b,c,d
}
//-----while 循环
var num = 1;
while (num<10){ //死循环实现建议
num++;
if(num%2==0){break;} //结束循环
}
//----变异的 while循环
var num = 10;
do{
console.log(num);
num--;
}while(num>=0);
2.js $.each(array,function(index,value){…})
说明:有两个参数,第一个(array)为待遍历的数组或对象,
第二个(function(index,value){…})为回调函数,
函数中的两个参数,
index为当前遍历到的元素下标或对象的key,
value为当前遍历到的数组元素或对象的值。
$.each(res.results, function(){
innerhtml +=’’+this.tqyy+’ ‘+this.jdmc+’ ‘+this.endtime+’’;
});
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
console.log(key+":"+val);
});
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
-
forEach
arr.forEach(function(item,index,array){…})
其中回调函数有3个参数,
item为当前遍历到的元素,
index为当前遍历到的元素下标,
array为数组本身。
forEach方法不会跳过null和undefined元素。比如数组[1,undefine,null,,2]中的四个元素都将被遍历到。
var arr=[1,2,3,4];
arr.forEach(function(item,index,arr){
arr[index]=2*val;
});将 arr内 每个元素*2;