js常用循环

一、$.each循环

var arr = [1,2,3,4,5];
$.each(arr, function(){
  console.log(this);
});
$.each(arr, function(index,ele){
  console.log(index + ':' + ele);
});

二、for循环

for(var i = 0;i<5;i++){
 console.log(i)
}

三、for in循环

let obj = {a:1, b:2, c:3};
for (let prop in obj) {    //prop指对象的属性名
console.log(prop, obj[prop]);
}
// 输出:
// a,1
// b,2
// c,3

四、forEach循环

(注意:forEach循环里面没办法用break跳出循环。而且在IE中无法实现,需要做兼容处理。)

let arr = ['123','abc','aaa'];
myArray.forEach(function (value, index) {
    console.log(value,index);
});
//输出
//"123",1
//"abc",2
//"aaa",3

五、for of循环

(ES6新增的循环方法,避开了for-in循环的所有缺陷,还可以正确响应break、continue和return语句)

//循环数组
let arr = ['123','abc','aaa'];
for(let item of arr){
    console.log(item);    //item指的的就是数组每一项的值。不是索引。
}
//输出
//'123'
//'abc'
//'aaa'

//遍历字符串
let name = 'Asher';
for (let char of name){
    console.log(char);         //A s h e r
}

//遍历Map集合
let mapArray = new Map();
for (let [key, value] of mapArray) {
   console.log(key,value);
}
//Set集合同理,不列举了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值