js中的循环方式

身为一名开发人员,工作中遍历数据是肯定得接触的,我准备来写写JS中各种遍历的方法。

1,for循环

对于循环应该是最常用的一种遍历方式了,通常用来遍历数组结构。

let arr = [a,b,d];
for (let i=0; i<arr.length; i++){
    console.log(i,arr[i]);
}

2,for...in循环

for...in语句用于对数组或者对象的属性进行循环操作。

for...in循环中的代码每执行一次,就会对数组或者对象的属性进行一次操作。

let obj={'name':'programmer','age':'22','height':'180'};
for(let i in obj){
    console.log(i,obj[i])
}

3,while循环

while用于循环作用基本一致,通常用来循环数组

cars=["BMW","Volvo","Saab","Ford"];
var i=0;
while (cars[i]){
    console.log(cars[i] + "<br>")
    i++;
};

4,do while循环

do while 是while的一个亲戚,它在循环开始前先执行一次操作,然后才进行判断,true就继续执行,false就结束循环。

let i = 3;
do{
    console.log(i)
    i--;
}
while(i>0);

5,forEach循环

扫描二维码关注公众号,回复: 4569080 查看本文章

forEach方法用于调用数组的每个元素,并将元素传递给回调函数。对于空数组不会执行回调函数。

let arr = [1,2,3];
arr.forEach(function(i,index){
    console.log(i,index)
})
// 1 0
// 2 1
// 3 2

6,map方法

map返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

let arr = [1,2,3];
let tt = arr.map(function(i){
    console.log(i)
    return i*2;
})
// [2,4,6]  tt

7,for...in循环

因为是es6引入到新特性中的,借鉴c ++,java,c#和python语言,引入for...in循环,作为遍历所有数据结构的统一方法。

var arr = ['a', 'b', 'c', 'd'];
for (let a of arr) {
    console.log(a); // a b c d
}

详细具体用法英语谚语详见阮一峰老师的ES6入门这本书

8,其他有遍历的数组API也有很多,不一一赘述了,上面ES6新特性里面就有很多类似的方法。

猜你喜欢

转载自blog.csdn.net/weixin_40776188/article/details/81865986