201602061615_《Javascript方法之map();filter();——以前一直很混》

/*"映射的意思,映射为一个新数组,一个经过一定运算的数组"*/
var arr=[1,3,5,6]; 
var computedArr = arr.map(function(item){

    return item*item*item;
    });

 console.log(computedArr);  //[1, 27, 125, 216]

 

Filter

创建一个新的匹配过滤条件的新数组。

例-1(无Filter):

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

for(var i= 0, l = arr.length; i< l; i++){
  if(arr[i].name === "orange" ){
    newArr.push(arr[i]);
    }
}; 

for(var j = 0;j<newArr.length;j++){
console.log("-------------------Filter results:-------------",newArr[j]);
};


/*
-------------------Filter results:---------------- Object {name: "orange", count: 5}
 -------------------Filter results:---------------- Object {name: "orange", count: 16} 
*/   

 

例-2(使用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";
});

for(var i=0;i<newArr.length;i++){console.log("Filter results:",newArr[i]);};

/*
 Filter results: Object {name: "orange", count: 5}
 Filter results: Object {name: "orange", count: 16}
*/

 

posted @ 2016-02-06 16:33  Coca-code  阅读(227)  评论(0编辑  收藏  举报