1. 程式人生 > >5個數組Array方法: indexOf、filter、forEach、map、reduce使用例項

5個數組Array方法: indexOf、filter、forEach、map、reduce使用例項

在ES5中,一共有9個Array方法 :

 Array.prototype.indexOf
 Array.prototype.lastIndexOf
 Array.prototype.every
 Array.prototype.some
 Array.prototype.forEach
 Array.prototype.map
 Array.prototype.filter
 Array.prototype.reduce
 Array.prototype.reduceRight

1. indexOf

  indexOf()方法返回在該陣列中第一個找到的元素位置,如果它不存在則返回-1。

輸入:

var arr = ['apple','orange','pear'];

console.log("found:", arr.indexOf("orange") );

輸出:

found: 1

2. filter

  該filter()方法建立一個新的匹配過濾條件的陣列。

輸入:

var arr = [
  {"name":"apple", "count": 2},
  {"name":"orange", "count": 5},
  {"name":"pear", "count": 3},
  {"name":"orange", "count": 16},
];

var
newArr = arr.filter(function(item){ return item.name=='orange'; }) console.log("Filter results:",newArr.toString());

輸出:

Filter results: [{"name":"orange","count":5},{"name":"orange","count":16}]

3. forEach

  forEach為每個元素執行對應的方法。

輸入:

var arr = [1,2,3,4,5,6,7,8];

arr.forEach(function
(item,index){
console.log("item:"+item+",index:"+index); });

輸出:

item:1,index:0
item:2,index:1
item:3,index:2
item:4,index:3
item:5,index:4
item:6,index:5
item:7,index:6
item:8,index:7

4. map()

  map()對陣列的每個元素進行一定操作(對映)後,會返回一個新的陣列,。

輸入:

var oldArr = 
[{first_name:"Colin",last_name:"Toh"},
{first_name:"Addy",last_name:"Osmani"},
{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
    return oldArr.map(function(item,index){
        item.full_name = [item.first_name,item.last_name].join(" ");
        return item;
    }); 
}
console.log(getNewArr());

輸出:

[{"first_name":"Colin","last_name":"Toh","full_name":"Colin Toh"},{"first_name":"Addy","last_name":"Osmani","full_name":"Addy Osmani"},{"first_name":"Yehuda","last_name":"Katz","full_name":"Yehuda Katz"}]

5. reduce()

  reduce()可以實現一個累加器的功能,將陣列的每個值(從左到右)將其降低到一個值。。

輸入:

var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){
  return arr.reduce(function(prev,next){
console.log("prev:"+JSON.stringify(prev)+",next:"+next)
    prev[next] = (prev[next] + 1) || 1;
    return prev;
  },{});
}

console.log(JSON.stringify(getWordCnt()));

輸出:

prev:{},next:apple
prev:{"apple":1},next:orange
prev:{"apple":1,"orange":1},next:apple
prev:{"apple":2,"orange":1},next:orange
prev:{"apple":2,"orange":2},next:pear
prev:{"apple":2,"orange":2,"pear":1},next:orange
VM401:11 {"apple":2,"orange":3,"pear":1}