map()方法的作用就是"映射",把原来的数组"映射"成一个新数组。
1.map()方法简介
map()方法返回一个新数组,由原数组中的每个元素调用一个回调函数后的返回值组成的新数组。
map()不会对空数组进行检测。
map()不会改变原始数组。
//a 0 b 1 c 2 d 3 其中arr为数组本身
let arr=["a","b","c","d"];
arr.map(function(currentValue,index,arr){
console.log(currentValue)
console.log(index)
});其中currentValue参数是必选的,表示当前遍历到的元素值
index可选,表示当前元素的索引
arr可选,表示当前元素所属的数组
2 数据项求平方
let nums=[1,2,3,4];
// [1, 4, 9, 16]
/*let squareNums = nums.map(function(item){
return item*item;
});*/
let squareNums = nums.map(item=>item*item);
console.log(squareNums);3 获得对象的属性
let userinfos = [{"id":1,"name":"张超"},{"id":2,"name":"肖洋"},{"id":3,"name":"李腾"}];
/* let names = userinfos.map(function(item){
return item.name;
});*/
let names = userinfos.map(item=>item.name);
//['张超', '肖洋', '李腾']
console.log(names);4 调用一个方法
let list = ["1","2","3"];
function parseInt10(item){
return parseInt(item,10);
}
function parseInt2(item){
return parseInt(item,2);
}
//[1,2,3]
let numList10 = list.map(parseInt10);
console.log(numList10);
//1 NaN NaN 因为在二进制中只有0 和 1
let numList2 = list.map(parseInt2);
console.log(numList2);
//1 NaN NaN,parseInt可以接收两个参数,默认第一个接收的为当前元素,第二个为索引号
//相当于 parseInt(1,0) 0默认按着十进制,所以为1 parseInt(2,1),2在1进制中没有所以NaN,parseInt(3,2),3在2进制中没有所以NaN
let numList = list.map(parseInt);
console.log(numList);5 和filter及reduce的区别
5.1filter()
filter()方法创建一个新数组,新数组中的元素是由过滤筛选数组中符合条件的所有元素
filter不会改变原数组
let boys = [{"id":1,"name":"张超","height":185},{"id":2,"name":"肖洋","height":180},{"id":3,"name":"李腾","height":178}];
//[{id: 1, name: '张超', height: 185},{id: 2, name: '肖洋', height: 180}]
let boy180s = boys.filter(boy=>boy.height>=180);
console.log(boy180s);5.2reduce()
reduce() 遍历数组,调用回调函数,将数组元素累加成一个值,reduce从索引最小值开始,reduceRight反向
reduce对空数组不会执行回调
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
function(total,currentValue, index,arr)
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。
initialValue 可选。传递给函数的初始值
如果没有初始值,那么第一个参数的初始值就是数组下标为0的元素,本次遍历从下标1开始
如果设置初始值,那么第一个参数的初始值就是用于计算的初始值,本次遍历从0开始
let boys = [{"id":1,"name":"张超","height":185},{"id":2,"name":"肖洋","height":180},{"id":3,"name":"李腾","height":178}];
let heights = boys.reduce(function(total,currentValue,index,arr){
return total+currentValue.height;
},0)
//543
console.log(heights);

0条评论
点击登录参与评论