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 可以抛出异常

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。