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循环

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...of循环

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM