{ let array = [1,2,3,4,5,6,7]; for (let i = 0; i < array.length; i++) { console.log(i,array[i]); } }
{ let array = ['aa','abc','ccr',154,'s1']; array.forEach(v=>{ //es6 console.log(v); }); array.forEach(function(v){ //es5 console.log(v); }); }
注意:在使用forEach遍歷數組以前必定要判斷數組是否已經定義!es6
{ let array = ['aa','abc','ccr',154,'s1']; for(let index in array) { console.log(index,array[index]); }; }
{ let A = {a:1,b:2,c:3,d:"hello world"}; for(let key in A) { //key 爲對象的鍵 console.log(k,A[k]); } }
{ let array = ['aa','abc','ccr',154,'s1']; for(let v of array) { console.log(v); }; let s = "helloabc"; for(let c of s) { console.log(c); } }
總結來講:for in老是獲得對像的key或數組,字符串的下標,而for of和forEach同樣,是直接獲得值。因此,for of不能對象用數組
{ let i = 0, x = ''; while (i<5) { console.log("The number is " + i + "<br>"); i++; } }
{ let i = 0, x = ''; do { console.log("The number is " + i + "<br>"); i++; } while (i<5); }