close

重新複習JavaScript : 不要再用for迴圈,還有更多選擇。

回檔參數

定義

Value

陣列元素的值。

index

陣列元素的數位索引。

fullarray

包含該元素的陣列物件。

forEach Method : 就把Array(months)中的元素(e.g: January)都有走一次

 

 var months = ['January', 'February', 'March', 'April', 'May', "June", "July", "August", "Septemer", "October", "November", "December"];
    
 months.forEach(function(value, index, fullArray){
        alert(value + " is month number " +(index + 1 )+ " of " + fullArray.length);
    });

 

實際案例 : http://plnkr.co/edit/SCNgSp?p=info

 

 

every Method : 就把Array(months)中的元素(e.g: January)都有走一次,但是回傳條件只要其中有一個元素不符合就會回傳False

 

 var months = ['January', 'February', 'March', 'April', 'May', "June", "July", "August", "Septemer", "October", "November", "December"];
    
  everyItemContainsR = months.every(function(value, index, fullArray){
        return value.indexOf("r") >= 0;
    });

 alert(everyItemContainsR); //false

 

結果 : False

實際案例 : http://plnkr.co/edit/r0QiEw?p=info

 

 

some Method : 就把Array(months)中的元素(e.g: January)都有走一次,但是回傳條件只要其中有一個元素符合就會回傳True

 

 var months = ['January', 'February', 'March', 'April', 'May', "June", "July", "August", "Septemer", "October", "November", "December"];
    
   someItemContainsR = months.some(function(value, index, fullArray){
       return value.indexOf("r") >= 0;
    });

 alert(someItemContainsR ); //True

 

結果 : True 

實際案例 : http://plnkr.co/edit/r0QiEw?p=info

 

 

map Method : 就把Array(months)中的元素(e.g: January)都有走一次,但是map 可以產生新的Array和執行一個function。

 

  var MonthsOftheYear = ['January', 'February', 'March'];
    
   MonthsFirstLetters = MonthsOftheYear.map(function(value, index, fullArray){
       return value + " starts with " + value.charAt(0);
       
   });
   
   alert(MonthsFirstLetters.join(", ")); //

 

結果 : January starts with M, February starts with T, March starts with W

實際案例 : http://plnkr.co/edit/W4rm4e?p=info

 

filter Method : 就把Array(months)中的元素(e.g: January)都有走一次,但是filter 可以過濾掉不符合條件的元素和執行一個function。

 

   var months = ['January', 'February', 'March', 'April', 'May', "June", "July", "August", "Septemer", "October", "November", "December"];
    
    monthsContainsR = months.filter(function(value, index, fullArray){
        return value.indexOf("r") >= 0;
    });
    
  
    alert(monthsContainsR.join(", "));

 

結果 : January, February, March, April, Septemer, October, November, December

實際案例 : http://plnkr.co/edit/4b2aN6

 

 

 

 

 

arrow
arrow
    創作者介紹
    創作者 Kenneth 的頭像
    Kenneth

    Kenneth的部落格

    Kenneth 發表在 痞客邦 留言(0) 人氣()