亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    深入了解JS中的for…of循環(huán)

    本篇文章帶大家深入了解一下JavaScript中的for…of循環(huán)。有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

    深入了解JS中的for...of循環(huán)

    for…of語句創(chuàng)建的循環(huán)可以遍歷對象。在ES6中引入的for…of可以替代另外兩種循環(huán)語句for…in和forEach(),而且這個新的循環(huán)語句支持新的迭代協(xié)議。for…of允許你遍歷可迭代的數(shù)據(jù)結(jié)構(gòu),比如數(shù)組、字符串、映射、集合等。

    語法

    for (variable of iterable) {     statement }
    • variable:每個迭代的屬性值被分配給variable

    • iterable:一個具有可枚舉屬性并且可以迭代的對象

    我們使用一些示例來闡述。

    Arrays

    array是簡單的列表,看上去像object。數(shù)組原型有多種方法,允許在其上執(zhí)行操作,比如遍歷。下面的示例使用for…of來對一個array進行遍歷操作:

    const iterable = ['mini', 'mani', 'mo'];  for (const value of iterable) {     console.log(value); }  // Output: // => mini // => mani // => mo

    其結(jié)果就是打印出iterable數(shù)組中的每一個值。

    Map

    Map對象持有key-value對。對象和原始值可以當(dāng)作一個keyvalue。Map對象根據(jù)插入的方式遍歷元素。換句話說,for...of在每次迭代中返回一個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元素的迭代是基于插入順序,每個值只能發(fā)生一次。如果你創(chuàng)建一個具有相同元素不止一次的Set,那么它仍然被認為是單個元素。

    const iterable = new Set([1, 1, 2, 2, 1]);  for (const value of iterable) {     console.log(value); }  // Output: // => 1 // => 2

    盡管我們創(chuàng)建的Set有多個12,但遍歷輸出的只有12

    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í)行迭代,并打印出每個索引上(index)的字符。

    Arguments Object

    把一個參數(shù)對象看作是一個類似數(shù)組的對象,與傳遞給函數(shù)的參數(shù)相對應(yīng)。這是一個用例:

    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ù)會接收傳入args()函數(shù)的任何參數(shù)。因此,如果我們將20個參數(shù)傳遞給args()函數(shù),我們將輸出20個參數(shù)。

    在上面的示例基礎(chǔ)上做一些調(diào)整,比如給args()函數(shù),傳入一個對象、數(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

    生成器是一個函數(shù),它可以退出函數(shù),稍后重新進入函數(shù)。

    function* generator(){      yield 1;      yield 2;      yield 3;  };  for (const g of generator()) {      console.log(g);  }  // Output: // => 1 // => 2 // => 3

    function* 定義一個生成器函數(shù),該函數(shù)返回生成器對象。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號