前台循环整理

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);
});
  1. 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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值