在開發中,循環是很經常使用的,在這裏總結下js的幾種循環:javascript
1.普通循環: for()java
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for(let i = 0; i < array.length; i++){ console.log(array[i]); };
2.簡單循環: for...ines6
index爲數組下標,從0開始,這種寫法能夠讓for循環的條件簡短些數組
for(let index in array){ console.log(array[index]); };
3.forEach: forEach(fn())函數
注意: 沒法用break跳出編碼
array.forEach(function(value) { console.log(value); }); // 函數可用箭頭函數簡寫(es6寫法,減小代碼) array.forEach(value=> { console.log(value); })
這裏注意,forEach的語法以下: value當前元素,index爲當前元素的索引值,arr當前元素所屬的數組對象;後面兩個值可選; spa
arr.forEach(function(value,index,arr){ // 這裏能夠寫本身的邏輯 });
4.ES6循環: for...of (a爲數組中的對象,在這裏是值,相似java中的增強for循環)code
在這裏說明下,這種循環比價簡潔,只是數組下標不可見,要想知道是哪一個,須要從新計算,不方便作數組刪除等操做,可根據業務需求選擇比較合適的循環對象
for(let a of array){ console.log(a); } // 除了遍歷字符串,這個遍歷器最大的優勢是能夠識別大於0xFFFF的碼點,傳統的for循環沒法識別這樣的碼點。 var text = String.fromCodePoint(0x20BB7); for (let i of text) { console.log(i); } // "𠮷" // String.fromCodePoint(num1[, ...[, numN]]) 靜態方法返回使用指定的代碼點序列建立的字符串。 // num1, ..., numN 一串 Unicode 編碼,識別32位的UTF-16字符