搜尋
首頁web前端前端問答es6新增循環有哪些

es6新增循環有哪些

Nov 07, 2022 pm 07:29 PM
javascriptes6循環結構循環遍歷

es6新增循環語句有一個:「for of」迴圈。 「for..of」語句可循環遍歷整個對象,是在迭代器生產的一系列值的循環;“for..of”循環的值必須是一個iterable(可迭代的),語法“for(當前值of 數組){...}」。 for-of循環不僅支援數組,還支援大多數類別數組物件;它也支援字串遍歷,會將字串視為一系列Unicode字元來進行遍歷。

es6新增循環有哪些

本教學操作環境:windows7系統、ECMAScript 6版、Dell G3電腦。

以前for迴圈,for in迴圈;而ES6新增迴圈:for of 迴圈:遍歷(迭代,迴圈)整個物件。

for..of

ES6新增了一個for..of循環,在迭代器生產的一系列值的循環。 for..of迴圈的值必須是一個iterable

var a = ["a", "b","c","d","e"]
for(var idx in a){
    console.log(idx)
}
// 0 1 2 3 4
for(var val of a){
    console.log(val)
}
// a b c d e

for..in在數組a的鍵/索引上循環,for..ofa的值上循環。 【相關推薦:javascript影片教學web前端

<span style="font-size: 18px;">ES6</span>之前的程式碼

var a = ["a", "b","c","d","e"]
for(var val, ret, it = a[Symbol.iterator]();(ret=it.next()) && !ret.done){
    val = ret.value
    console.log(val)
}
// a b c d e

在底層,for..of循環向iterable請求一個迭代器,然後重複呼叫這個迭代器把它產生的值賦給循環迭代變數。

JavaScript預設為iterable的標準內建值包含:

  • Array
  • Strings
  • Generators
  • Collections/TypedArrays

##字串迭代方式
for(var c of "hello"){
    console.log(c)
}
// h e l l o

原生字串值被強制類型轉換到等價的String封裝物件中,它是一個

iterable

for(XYZ of ABC)<span style="font-size: 18px;"></span>

對於

XYZ這個位置既可以是賦值表達式,也可以是宣告。下面看個賦值表達式的範例:

var o = {}
for(o.a of [1,2,3]){
    console.log(o.a)
}
o // {a:3}
for({x:o.a} of [{x:1},{x:2},{x:3}]){
    console.log(o.a)
}
o // {a:3}

透過

break,continue,return提前終止迴圈。

自訂迭代器

透過對底層的了解,

for..ofiterable請求一個迭代器,然後重複呼叫這個迭代器把它產生的值賦給循環迭代變數。那我可以自訂一個iterable

var o = {
    [Symbol.iterator](){
        return this
    },
    next(){
        if(!val){
            val = 1
        }else{
            val ++
        }
        return {value:val, done:val== 6}
    }
}
for(var val of o[Symbol.iterator]()){
    console.log(val)
}

由此可見,自訂迭代器滿足兩個條件,

[Symbol.iterator]屬性,在傳回的物件中有next方法, next方法傳回值必須是{value:xx,done:xx}的形式,如果遇到done:true,則循環結束。

結語:以上就是for..of循環的全部內容,它可以循環可迭代物件。

擴充知識:為什麼要引進 for-of?

要回答這個問題,我們先來看看ES6之前的3 種for 迴圈有什麼缺陷:

##forEach 不能break 和return;
  • for-in 缺點更明顯,它不僅遍歷數組中的元素,還會遍歷自訂的屬性,甚至原型鏈上的屬性都被存取。而且,遍歷數組元素的順序可能是隨機的。
  • 所以,鑑於上述種種缺陷,我們需要改進原先的 for 迴圈。但 ES6 不會破壞你已經寫好的 JS 程式碼。目前,成千上萬的 Web 網站依賴 for-in 循環,其中一些網站甚至將其用於陣列遍歷。如果想要透過修正 for-in 迴圈增加陣列遍歷支援會讓這一切變得更加混亂,因此,標準委員會在 ES6 中增加了一種新的迴圈語法來解決目前的問題,即 for-of 。

那 for-of 到底可以做什麼呢?

跟 forEach 相比,可以正確回應 break, continue, return。
  • for-of 迴圈不僅支援數組,還支援大多數類別數組對象,例如 DOM nodelist 物件。
  • for-of 迴圈也支援字串遍歷,它將字串視為一系列 Unicode 字元來進行遍歷。
  • for-of 也支援 Map 和 Set (兩者皆為 ES6 中新增的型別)物件遍歷。
  • 總結一下,for-of 迴圈有以下幾個特徵:
  • 这是最简洁、最直接的遍历数组元素的语法。
  • 这个方法避开了 for-in 循环的所有缺陷。
  • 与 forEach 不同的是,它可以正确响应 break、continue 和 return 语句。
  • 其不仅可以遍历数组,还可以遍历类数组对象和其他可迭代对象。

但需要注意的是,for-of循环不支持普通对象,但如果你想迭代一个对象的属性,你可以用
for-in 循环(这也是它的本职工作)。

最后要说的是,ES6 引进的另一个方式也能实现遍历数组的值,那就是 Iterator。上个例子:

const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];
const iter = arr[Symbol.iterator]();
 
iter.next() // { value: &#39;a&#39;, done: false }
iter.next() // { value: &#39;b&#39;, done: false }
iter.next() // { value: &#39;c&#39;, done: false }
iter.next() // { value: undefined, done: true }

前面的不多说,重点描述for-of

for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象

for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:

window.onload=function(){ 
   const arr = [55,00, 11, 22];
   arr.name = "hello";
  // Array.prototype.FatherName = &#39;FatherName&#39;;
   /*for(let key in arr){
    console.log(&#39;key=&#39;+key+&#39;,key.value=&#39;+arr[key]);
   }*/
   /* arr.forEach((data) => {console.log(data);});*/
  /* arr.forEach((data,index,arr) => {console.log(data+&#39;,&#39;+index+&#39;,&#39;+arr);});*/
  /*for(let key of arr){
    console.log(key);
  }*/
  var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  const stringArr = [string1,string2];
  for(let key of stringArr){
    console.log(key);
  }
  for(let key of string1){
    console.log(key);
  }
}

结果:

es6新增循環有哪些

现在,只需记住:

  • 这是最简洁、最直接的遍历数组元素的语法
  • 这个方法避开了for-in循环的所有缺陷
  • 与forEach()不同的是,它可以正确响应break、continue和return语句

for-in循环用来遍历对象属性。

for-of循环用来遍历数据—例如数组中的值。

它同样支持Map和Set对象遍历。

Map和Set对象是ES6中新增的类型。ES6中的Map和Set和java中并无太大出入。

SetMap类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set中,没有重复的key。

要创建一个Set,需要提供一个Array作为输入,或者直接创建一个空Set

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3

es6新增循環有哪些

重复元素在Set中自动被过滤:

var s = new Set([1, 2, 3, 3, '3']);
console.log(s); // Set {1, 2, 3, "3"}

es6新增循環有哪些

通过add(key)方法可以添加元素到Set中,可以重复添加,但不会有效果:

var s = new Set([1, 2, 3]);
s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Set {1, 2, 3, 4}

通过delete(key)方法可以删除元素:

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}

Set对象可以自动排除重复项

var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  var string3 = &#39;opqrstuvwxyc&#39;;
  var string4 = &#39;opqrstuvwxyz&#39;;
 
  const stringArr = [string1,string2,string3,string4];
 
 
 var newSet = new Set(stringArr);
  for(let key of newSet){
    console.log(key);
  }

结果:

es6新增循環有哪些

Map对象稍有不同:内含的数据由键值对组成,所以你需要使用解构(destructuring)来将键值对拆解为两个独立的变量:

for (var [key, value] of phoneBookMap) {   
console.log(key + "&#39;s phone number is: " + value);
}

 示例

var m = new Map([[1, &#39;Michael&#39;], [2, &#39;Bob&#39;], [3, &#39;Tracy&#39;]]);
  var map = new Map([[&#39;1&#39;,&#39;Jckey&#39;],[&#39;2&#39;,&#39;Mike&#39;],[&#39;3&#39;,&#39;zhengxin&#39;]]);
  map.set(&#39;4&#39;,&#39;Adam&#39;);//添加key-value
  map.set(&#39;5&#39;,&#39;Tom&#39;);
  map.set(&#39;6&#39;,&#39;Jerry&#39;);
  console.log(map.get(&#39;6&#39;));
  map.delete(&#39;6&#39;);
   console.log(map.get(&#39;6&#39;));
  for(var [key,value] of map) {
    console.log(&#39;key=&#39;+key+&#39; , value=&#39;+value);
  }

结果:

es6新增循環有哪些

以上是es6新增循環有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
CSS:我可以在同一DOM中使用多個ID嗎?CSS:我可以在同一DOM中使用多個ID嗎?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5的目的:創建一個更強大,更容易訪問的網絡HTML5的目的:創建一個更強大,更容易訪問的網絡May 14, 2025 am 12:18 AM

html5aimstoenhancewebcapabilities,Makeitmoredynamic,互動,可及可訪問。 1)ITSupportsMultimediaElementsLikeAnd,消除innewingtheneedtheneedtheneedforplugins.2)SemanticeLelelemeneLementelementsimproveaCceccessibility inmproveAccessibility andcoderabilitile andcoderability.3)emply.3)lighteppoperable popperappoperable -poseive weepivewebappll

HTML5的重要目標:增強網絡開發和用戶體驗HTML5的重要目標:增強網絡開發和用戶體驗May 14, 2025 am 12:18 AM

html5aimstoenhancewebdevelopmentanduserexperiencethroughsemantstructure,多媒體綜合和performanceimprovements.1)SemanticeLementLike like,和ImproVereAdiability and ImproVereAdabilityActibility.2)and tagsallowsemlessallowseamelesseamlessallowseamelesseamlesseamelesseamemelessmultimedimeDiaiaembediiaembedplugins.3)。 3)3)

HTML5:安全嗎?HTML5:安全嗎?May 14, 2025 am 12:15 AM

html5isnotinerysecure,butitsfeaturescanleadtosecurityrisksifmissusedorimproperlyimplempled.1)usethesand andboxattributeIniframestoconoconoconoContoContoContoContoContoconToconToconToconToconToconTedContDedContentContentPrenerabilnerabilityLikeClickLickLickLickjAckJackJacking.2)

與較舊的HTML版本相比,HTML5目標與較舊的HTML版本相比,HTML5目標May 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS:使用ID選擇器不好嗎?CSS:使用ID選擇器不好嗎?May 13, 2025 am 12:14 AM

使用ID選擇器在CSS中並非固有地不好,但應謹慎使用。 1)ID選擇器適用於唯一元素或JavaScript鉤子。 2)對於一般樣式,應使用類選擇器,因為它們更靈活和可維護。通過平衡ID和類的使用,可以實現更robust和efficient的CSS架構。

HTML5:2024年的目標HTML5:2024年的目標May 13, 2025 am 12:13 AM

html5'sgoalsin2024focusonrefinement和optimization,notNewFeatures.1)增強performanceandeffipedroptimizedRendering.2)inviveAccessibilitywithRefinedwithRefinedTributesAndEllements.3)explityconcerns,尤其是withercercern.4.4)

HTML5試圖改進的主要領域是什麼?HTML5試圖改進的主要領域是什麼?May 13, 2025 am 12:12 AM

html5aimedtotoimprovewebdevelopmentInfourKeyAreas:1)多中心供應,2)語義結構,3)formcapabilities.1)offlineandstorageoptions.1)html5intoryements html5introctosements introdements and toctosements and toctosements,簡化了inifyingmediaembedingmediabbeddingingandenhangingusexperience.2)newsements.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!