本篇文章帶大家深入了解一下JavaScript中的for…of循環(huán)。有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對你有所幫助。
for…of語句創(chuàng)建的循環(huán)可以遍歷對象。在ES6中引入的for…of可以替代另外兩種循環(huán)語句for…in和forEach(),而且這個(gè)新的循環(huán)語句支持新的迭代協(xié)議。for…of允許你遍歷可迭代的數(shù)據(jù)結(jié)構(gòu),比如數(shù)組、字符串、映射、集合等。
語法
for (variable of iterable) { statement }
-
variable:每個(gè)迭代的屬性值被分配給variable
-
iterable:一個(gè)具有可枚舉屬性并且可以迭代的對象
我們使用一些示例來闡述。
Arrays
array是簡單的列表,看上去像object。數(shù)組原型有多種方法,允許在其上執(zhí)行操作,比如遍歷。下面的示例使用for…of來對一個(gè)array進(jìn)行遍歷操作:
const iterable = ['mini', 'mani', 'mo']; for (const value of iterable) { console.log(value); } // Output: // => mini // => mani // => mo
其結(jié)果就是打印出iterable
數(shù)組中的每一個(gè)值。
Map
Map
對象持有key-value
對。對象和原始值可以當(dāng)作一個(gè)key
或value
。Map
對象根據(jù)插入的方式遍歷元素。換句話說,for...of
在每次迭代中返回一個(gè)kay-value
對的數(shù)組。
const iterable = new Map([['one', 1], ['two', 2]]); for (const [key, value] of iterable) { console.log(`Key: ${key} and Value: ${value}`); } // Output: // => Key: one and Value: 1 // => Key: two and Value: 2
Set
Set
對象允許你存儲任何類型的唯一值,這些值可以是原始值或?qū)ο蟆?code>Set對象只是值的集合。Set
元素的迭代是基于插入順序,每個(gè)值只能發(fā)生一次。如果你創(chuàng)建一個(gè)具有相同元素不止一次的Set
,那么它仍然被認(rèn)為是單個(gè)元素。
const iterable = new Set([1, 1, 2, 2, 1]); for (const value of iterable) { console.log(value); } // Output: // => 1 // => 2
盡管我們創(chuàng)建的Set
有多個(gè)1
和2
,但遍歷輸出的只有1
和2
。
String
字符串用于以文本形式存儲數(shù)據(jù)。
const iterable = 'javascript'; for (const value of iterable) { console.log(value); } // Output: // => "j" // => "a" // => "v" // => "a" // => "s" // => "c" // => "r" // => "i" // => "p" // => "t"
在這里,對字符串執(zhí)行迭代,并打印出每個(gè)索引上(index
)的字符。
Arguments Object
把一個(gè)參數(shù)對象看作是一個(gè)類似數(shù)組的對象,與傳遞給函數(shù)的參數(shù)相對應(yīng)。這是一個(gè)用例:
function args() { for (const arg of arguments) { console.log(arg); } } args('a', 'b', 'c'); // Output: // => a // => b // => c
你可能在想,到底發(fā)生了什么?正如我前面說過的,當(dāng)調(diào)用函數(shù)時(shí),參數(shù)會(huì)接收傳入args()
函數(shù)的任何參數(shù)。因此,如果我們將20
個(gè)參數(shù)傳遞給args()
函數(shù),我們將輸出20
個(gè)參數(shù)。
在上面的示例基礎(chǔ)上做一些調(diào)整,比如給args()
函數(shù),傳入一個(gè)對象、數(shù)組和函數(shù):
function fn(){ return 'functions'; } args('a', 'w3cplus', 'c',{'name': 'airen'},['a',1,3],fn()); // Output: // => "a" // => "w3cplus" // => "c" // => Object { // => "name": "airen" // => } // => Array [ // => "a", // => 1, // => 3 // => ] // => "functions"
Generators
生成器是一個(gè)函數(shù),它可以退出函數(shù),稍后重新進(jìn)入函數(shù)。
function* generator(){ yield 1; yield 2; yield 3; }; for (const g of generator()) { console.log(g); } // Output: // => 1 // => 2 // => 3
function* 定義一個(gè)生成器函數(shù),該函數(shù)返回生成器對象。