javascript for循环的几种写法

记录一下平时常用的for循环的方法

1.for

```

let list =[1,2,3,4,5];

for(let index = 0; index < list.length; index++){

    console.log(index);         //0 1 2 3 4  获取下标

    console.log(list[index]);   //1 2 3 4 5  获取数组中的元素

}

```

2.forEach

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

```

const arraySparse = [1,2,3];

arraySparse.forEach(function(element,index,array){

    console.log(element);  // 1  2  3

    console.log(index);   //0  1   2

});

```

3.for.....in

它最常用的地方应该是用于调试,可以更方便的去检查对象属性

```

let list =[1,2,3];

for(let i in list){

    console.log(i +'&'+ list[i]);   //0&1 1&2 2&3

}

```

循环将遍历对象本身的所有可枚举属性,以及对象从其构造函数原型中继承的属性 

```

Object.prototype.objCustom = function() {}; 

Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];

iterable.foo = 'hello';

for (let i in iterable) {

  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"

}

```

不能保证for ... in将以任何特定的顺序返回索引。

```

var a = {1:"a",4:"d",3:"c",2:"b"};

for(var i in a)

    console.log(i + ": " + a[i])    // 1:a 2:b 3:c 4:d

```

4.for.....of

遍历可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)要迭代的数据(IE 浏览器不支持)

```

const array1 = ['1', '2', '3'];

for (let i of array1) {

      console.log(i);

}

```

对于for...of,for,for...in的循环,可以由break中止或跳出循环 ,arr.forEach 可以抛出异常

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值