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