1 var arr = ["first","second","third","fourth",3,5,8]; 2 for(var i = 0; i < arr.length;i++){ 3 console.log(arr[i]); 4 } 5 //輸出: 6 first 7 second 8 third 9 fourth 10 3 11 5 12 8
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 for(var i in arr){ 3 console.log(arr[i] +'/' + i); 4 } 5 //輸出結果爲: 6 first/0 7 second/1 8 third/2 9 fourth/3 10 3/4 11 5/5 12 8/6
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 for(var item of arr){ 3 console.log(item); 4 } 5 //輸出結果: 6 first 7 second 8 third 9 fourth 10 3 11 5 12 8
雖然for… in 、 for… of 都可以變歷數組,可是二者仍是有很大區別的,先說結論:數組
二者的主要區別在於他們的迭代方式 函數
2.foreach方法:被傳遞給foreach的函數會在數組的每一個元素上執行一次,元素做爲參數傳遞給該函數測試
1 var arr = ["first","second","third","fourth",3,5,8]; 2 //element 表示arr的單元項,index 表示arr單元項對應的索引值 3 arr.forEach(function(element,index){ 4 console.log(element + '/' + index); 5 6 }) 7 //輸出結果: 8 first/0 9 second/1 10 third/2 11 fourth/3 12 3/4 13 5/5 14 8/6
1 var arr1 = ["first","second", ,"fourth",3,5,8]; 2 arr1.forEach(function(element,index){ 3 console.log(element + '/' + index); 4 5 }) 6 //輸出結果 7 first/0 8 second/1 9 fourth/3 10 3/4 11 5/5 12 8/6
1 var arr = ["first","second",'third' ,"fourth"]; 2 var arr2 = arr.map(function(item){ 3 return item.toUpperCase(); 4 }) 5 console.log(arr2); 6 //輸出: 7 [FIRST,SECOND,THIRD, FOURTH]
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var arr3 = arr.filter(function(item){ 3 if(typeof item == 'number'){ 4 return item; 5 } 6 }) 7 console.log(arr3); 8 //輸出結果: 9 [3,5,8]
當數組中的元素在測試條件時返回 true 時, find() 返回符合條件的元素,以後的值不會再調用執行函數。若是沒有符合條件的元素返回 undefinedspa
1 var arr = [1,2,3,4,5,6,7]; 2 var newArr = arr.find(function(elem){ 3 return elem>5; 4 }); 5 console.log(newArr); 6 //輸出結果 7 6
every()與filter()的區別是:後者會返回全部符合過濾條件的元素;前者會判斷是否是數組中的全部元素都符合條件,而且返回的是布爾值code
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var bol = arr.every(function(element){ 3 if(typeof element == 'string'){ 4 return element; 5 } 6 }) 7 console.log(bol); //false
every()與some()的區別是:前者要求全部元素都符合條件才返回true,後者要求只要有符合條件的就返回true對象
1 var arr = ["first","second",'third' ,"fourth",3,5,8]; 2 var bol = arr.some(function(element){ 3 if(typeof element == 'string'){ 4 return element; 5 } 6 }) 7 console.log(bol); //true
8.findindex() ES6數組新API,找到符合條件的索引並返回blog
1 var ages = [3, 10, 18, 20]; 2 3 function checkAdult(age) { 4 return age >= 18; 5 }
function(currentValue, index,arr)索引
參數currentValue:必需。當前元素element
index:可選。當前元素的索引回調函數
arr:可選.當前元素所屬的數組對象