您的位置:首页 > 其它

《ES6基础教程》之 map、forEach、filter indexOf 用法

2015-08-04 16:15 651 查看
1,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());


2,forEach 为每个元素执行对应的方法。

var arr=[1,2,3,4,5,6,7,8];
for ( var i =0,l= arr.length;i<l;i++) {
console.log(arr[i]);
};
arr.forEach(function(item,index){
console.log(item);
});


3,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]);
}
}
var newArr=arr.filter(function(){
return item.name==="orange";
});
console.log("Filer results",newArr);


4,indexOf方法返回数组中的找到的第一个元素的位置,若不存在返回-1。

var arr = ['apple','orange','pear'];
console.log("found:", arr.indexOf("orange") != -1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: