【ECMAScript5】ECMAScript5中有关数组的常用方法

1.indexOf()

此方法返回在改数组中第一个找到的元素位置,如果它不存在则返回-1

var arr = ['apple','orange','pear'];
 
console.log("found:", arr.indexOf("orange") != -1); //true

2.filter(fn)

此方法创建一个新的匹配过滤条件的数组

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);// [{"name":"orange", "count": 5},{"name":"orange", "count": 16}]

3.forEach(fn)

此方法用来替换for循环

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

4.map()

对数组的每个元素进行一定的操作(映射)后,会返回一个新的数var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"}];

function getNewArr(){
     
  return oldArr.map(function(item,index){
    item.full_name = [item.first_name,item.last_name].join(" ");
    return item;
  });
   
}
 
getNewArr();//[{first_name:"Colin",last_name:"Toh",full_name:"Colin Toh"},{first_name:"Addy",last_name:"Osmani" fll_name:'Addy Osmani'}]
项目中常用到的场景: 将数组中的某项以字符串的形式get给后台

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
oldArr.map(function(item,index){return item.first_name;}).join();//"Colin,Addy,Yehuda"
或者
oldArr.map(item => item.first_name).join();//"Colin,Addy,Yehuda"
 

5.reduce(callbackfn [ , initialValue ] )

可以实现一个累加器的功能,将数组的每个值(从左到右)将其降低到一个值

应用场景“统计一个数组中不重复单词

之前解决方案:
var
arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ var obj = {}; for(var i= 0, i < arr.length; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } console.log(getWordCnt());
//{apple: 2, orange: 3, pear: 1}


使用reduce()
var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getWordCnt());//

 

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from

     https://www.cnblogs.com/leejersey/p/5466091.html

作者:smile.轉角

QQ:493177502

posted on 2018-01-19 17:22  smile轉角  阅读(257)  评论(0编辑  收藏  举报

导航