es6:陣列函式用法
阿新 • • 發佈:2019-02-15
1:map 俗稱對映
let arr=[12,5,8];
let result=arr.map(item => item*2);
console.log(result);// [24, 10, 16]
let score=[19, 85, 99, 25, 90]; let result=score.map(item=>item>=60?'及格':'不及格'); console.log(result); //不及格,及格,及格,不及格,及格
2:reduce:俗稱累加
3:filter:過濾let arr=[10,25,32,41]; let sum=arr.reduce(function (tmp, item, index){ //alert(tmp+','+item+','+index); console.log(tmp+';'+item+';'+index+';'); //10;25;1; //35;32;2; //67;41;3; return tmp+item; }); console.log(sum); // 求和 108 let ave=arr.reduce(function (tmp, item, index){ if(index!=arr.length-1){ //不是最後一次 return tmp+item; }else{ //最後一次 return (tmp+item)/arr.length; } }); console.log(ave); // 求平均值 27
let arr=[12,5,8,99,27,36,75,11];
let result=arr.filter(item=>item%3==0);
console.log(result);[12, 99, 27, 36, 75]
let arr=[ {title: '男士襯衫', price: 75}, {title: '女士包', price: 57842}, {title: '男士包', price: 65}, {title: '女士鞋', price: 27531} ]; let result=arr.filter(json=>json.price>=10000); console.log(result);//{title: "女士包", price: 57842} {title:"女士鞋",price: 27531}
4:forEach:遍歷
let arr=[12,5,8,9];
arr.forEach((item,index)=>{
console.log(index+': '+item); //0: 12; 1: 5; 2: 8; 3: 9;
});