1.for循環
//有人喜歡使用一個臨時變量把長度緩存起來,說是數據量大時效果更好(我本人沒有去驗證)
for(j = 0,len=arr.length; j < len; j++) { //執行代碼 }
分析可用功能: 可以使用break和continue
2.forEach
//遍歷數組中的每一項,沒有返回值,對原數組沒有影響,不支持IE
//1 沒有返回值
arr.forEach((value,index,array)=>{//箭頭函數的寫法
//執行代碼
}) arr.forEach(function (value,index,array){//傳統寫法
//執行代碼
})
//參數:value數組中的當前項, index當前項的索引, array原始數組;
//數組中有幾項,那么傳遞進去的匿名回調函數就需要執行幾次;
分析可用功能 :break和continue都不可使用(需要自己用其他方式來控制break和continue,后面我寫了關於這個),return的作用是相當於continue
3.For/In 循環
循環遍歷對象的屬性會更佳(當然也可以遍歷數組),在Js中for in 是用來循環遍歷對象的屬性的,但是這個功能是有局限的,
所遍歷的屬性必須是對象自定義的屬性,對象的內置屬性無法進行遍歷。(IE6/7/8瀏覽器不支持)
var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; }
//x為對象的某個屬性
4.for/of 循環
for...of 語句創建一個循環來迭代可迭代的對象。在 ES6 中引入的 for...of 循環,以替代 for...in 和 forEach() ,並支持新的迭代協議。for...of 允許你遍歷 Arrays(數組), Strings(字符串), Maps(映射), Sets(集合)等可迭代的數據結構等。
4.1 Arrays(數組)
const iterable = ['mini', 'middle', 'mo']; for (const value of iterable) { console.log(value); }
//打印的是iterable 數組中的每一個值mini,middle,mo
4.2 Maps(映射)
Map 對象就是保存 key-value(鍵值) 對。對象和原始值可以用作 key(鍵)或 value(值)。Map 對象根據其插入方式迭代元素。換句話說, for...of 循環將為每次迭代返回一個 key-value(鍵值) 數組。
const iterable = new Map([['one', 1], ['two', 2]]); for (const [key, value] of iterable) { console.log(`Key: ${key} and Value: ${value}`); }
//輸出的是
// Key: one and Value: 1
// Key: two and Value: 2
4.3 String(字符串)
const iterable = 'javascript'; for (const value of iterable) { console.log(value); }
//輸出的是
// "j","a",.....依次
4.4 JavaScript 提供了四種已知的終止循環執行的方法:break、continue、return 和 throw
(注意return不要出現在循環體中,是一種錯誤語法,return用於函數體返回值)
const iterable = ['mini', 'middle', 'mo']; for (const value of iterable) { console.log(value); break; }
提示:我們常用return false來阻止提交表單或者繼續執行下面的代碼,通俗的來說就是阻止執行默認的行為
4.5 普通對象不可迭代
for...of 循環僅適用於迭代。 而普通對象不可迭代
const obj = { fname: 'foo', lname: 'bar' }; for (const value of obj) { console.log(value); }
//報錯了 TypeError: obj[Symbol.iterator] is not a function
value