高阶函数应用

一、map

 1、替换数组元素:

var arr1 = new Array(6)
arr1[0] = { key:"a",name:"b",value:"c"}
arr1[1] = { key:"d",name:"e",value:"f"}
arr1[2] = { key:"g",name:"h",value:"i"}
arr1[3] = { key:"j",name:"k",value:"l"}
var arr=arr1.map(item=>{
if(item.name==='h'){
return { key:"gg",name:"hh",value:"ii"}
}
return item;
});
console.log(arr);
console.log(arr1);

输出的数组arr是复制原数组得到的一个新的数组,原数组arr1并没有发生任何变化,输出结果如下:
[ { key: 'a', name: 'b', value: 'c' },
  { key: 'd', name: 'e', value: 'f' },
  { key: 'gg', name: 'hh', value: 'ii' },
  { key: 'j', name: 'k', value: 'l' },
  ,
   ]
[ { key: 'a', name: 'b', value: 'c' },
  { key: 'd', name: 'e', value: 'f' },
  { key: 'g', name: 'h', value: 'i' },
  { key: 'j', name: 'k', value: 'l' },
  ,
   ]
补充:创建数组有两种方式,第一种 new Array(1,2,3); 即以上实例使用的方式,第二种就是直接使用:[1,2,4] , 建议使用第二种;
   数组可以包括任意类型。

2、构造新数组:
var arr1 = new Array(6)
arr1[0] = { key:"a",name:"b",value:"c"}
arr1[1] = { key:"d",name:"e",value:"f"}
arr1[2] = { key:"g",name:"h",value:"i"}
arr1[3] = { key:"j",name:"k",value:"l"}
let arr=arr1.map(item => {
return {name: item.name, value: item.value};
});
console.log(arr);


[ { name: 'b', value: 'c' },
  { name: 'e', value: 'f' },
  { name: 'h', value: 'i' },
  { name: 'k', value: 'l' },
  ,
   ]
3、利用索引设置'key':
var arr1 = new Array(6)
arr1[0] = { key:"a",name:"b",value:"c"}
arr1[1] = { key:"d",name:"e",value:"f"}
arr1[2] = { key:"g",name:"h",value:"i"}
arr1[3] = { key:"j",name:"k",value:"l"}
var arr=arr1.map((item, index)=>{
return {key:index,value:item};
});
console.log(arr);


[ { key: 0, value: { key: 'a', name: 'b', value: 'c' } },
  { key: 1, value: { key: 'd', name: 'e', value: 'f' } },
  { key: 2, value: { key: 'g', name: 'h', value: 'i' } },
  { key: 3, value: { key: 'j', name: 'k', value: 'l' } },
  ,
   ]


二、Object.assign(target,...params)
var arr1 = new Array(6)
arr1[0] = { key:"a",name:"b",value:"c"}
arr1[1] = { key:"d",name:"e",value:"f"}
arr1[2] = { key:"g",name:"h",value:"i"}
arr1[3] = { key:"j",name:"k",value:"l"}
var arr=arr1.map(item=>{
item.name='kk';
item.value='56789';
return Object.assign(item,{index:1});
});
console.log(arr);


输出结果如下:
[ { key: 'a', name: 'kk', value: '56789', index: 1 },
  { key: 'd', name: 'kk', value: '56789', index: 1 },
  { key: 'g', name: 'kk', value: '56789', index: 1 },
  { key: 'j', name: 'kk', value: '56789', index: 1 },
  ,
   ]
很明显该函数的作用是将params(参数可以任意多个)复制给target。

三、findIndex()
  根据数组元素获取该元素在数组中的索引。
var arr1 = new Array(6)
arr1[0] = { key:"a",name:"b",value:"c"}
arr1[1] = { key:"d",name:"e",value:"f"}
arr1[2] = { key:"g",name:"h",value:"i"}
arr1[3] = { key:"j",name:"k",value:"l"}
const index=arr1.findIndex((value) => {
return value.key === "j"
});
const index2=arr1.findIndex((value) => value.key === "j");
console.log(index2+index);
const arr2=arr1[arr1.findIndex((value) => value.key === "j")];
console.log(arr2);

输出结果如下:

6
{ key: 'j', name: 'k', value: 'l' }


四、filter()
比较常用。
 



posted @ 2017-03-13 16:49  iam雪鹰  阅读(228)  评论(0编辑  收藏  举报