【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
作者:smile.轉角
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎关注我,一起进步!扫描下方二维码即可加我QQ