var arr =[1,2,3,4,5,6] //全文通用數組,個別除外
while
var i=0; while(i<=arr.length-1){ //條件需要有限制,故<=,否則會死循環 console.log(arr[i],i) i++;//更新下標 }
do while
var i=0; do{ console.log(arr[i],i) i++; }while(i<=arr.length-1);//下標從0開始,length-1
for
for(var i = 0;i<arr.length;i++){ console.log(i,arr[i]) }
for in
for(key in arr){ console.log(key,arr[key]) }
ES6語法
//Array.fromIE不識別,IE的兼容寫法。
//可以把類數組對象轉換為真正的數組
if(!Array.from){ Array.from = function (el) { return Array.apply(this, el); } }
Set
var a=[1,1,1]; var b=new Set(a);//去重 console.log(b) b.add('li')//添加 b.delete('li') //刪除 b.has('li') //返回true false; b.clear()//清空
Map
var eMap = new Map([ ['a', 1],['b', 2],['c', 3] ]); eMap.get('a') //1 //獲取值 eMap.has('b')//true //檢測key是否存在,返回true false; eMap.delete('c') //刪除 eMap.set('c',3) //添加 eMap.clear()//清空 //相當於返回一個新數組 arr.map(function(x){ if(x==3){
return x*3
} return x
}) arr.map((x)=>{ if(x==3){
return x*3
} return x })
forEach
//兩個參數 x數組內容,y數組下標
arr.forEach((x,y)=>{ console.log(x,y) })
//不支持IE9以下,但不包括IE9,IE8兼容寫法
//原文鏈接:https://www.cnblogs.com/guxiaosao/p/5179842.html
if ( !Array.prototype.forEach ) { Array.prototype.forEach = function forEach( callback, thisArg ) { var T, k; if ( this == null ) { throw new TypeError( "this is null or not defined" ); } var O = Object(this); var len = O.length >>> 0; if ( typeof callback !== "function" ) { throw new TypeError( callback + " is not a function" ); } if ( arguments.length > 1 ) { T = thisArg; } k = 0; while( k < len ) { var kValue; if ( k in O ) { kValue = O[ k ]; callback.call( T, kValue, k, O ); } k++; } }; }
for of
//支持大多數類數組對象 參考https://developer.mozilla.org/en-US/docs/Web/API/NodeList
//不支持普通對象遍歷 如:{ } 會報錯 is not iterable
//IE不支持
for(var i of arr){ console.log(i,arr[i-1])//for of的下標從1開始,故減1 }
//部分類數組對象 //原文鏈接: https://www.cnblogs.com/baiyunke/p/7821299.html
// 字符串 var str = "hello"; for (let s of str) { console.log(s); // h e l l o } // DOM NodeList對象 let paras = document.querySelectorAll("p"); for (let p of paras) { p.classList.add("test"); } // arguments對象 function printArgs() { for (let x of arguments) { console.log(x); } } printArgs('a', 'b');// 'a' 'b'
//循環控制語句
//break:當前條件成立且執行后跳出。 //continue:跳過當前成立條件,繼續執行循環。 //for循環,continue之后執行語句,是跳過條件的新下標。 //while、do-while循環,continue需放到i++之后使用,否則,continue將跳過i++進入死循環。 for(var i = 1; i < 10; i++){ if(i == 4){ continue; } console.log(i);//1 2 3 5 6 7 8 9 } for(var i = 1; i < 10; i++){ if(i == 4){ break; } console.log(i);//1 2 3 }
//箭頭函數單行語句可以簡寫,如:arr.map((x)=>x);
//ES6新增了 遍歷器(Iterator)機制 Iterator詳解 : http://es6.ruanyifeng.com/#docs/iterator
//ES6語法推薦使用編譯插件來處理兼容性問題 如:babel
//以上為理解、原文、參考、暫時就想到這么多