感谢师傅大佬的教育
今天学到的知识点:
forEach(遍历) VS map(映射) VS reduce(聚合)
1.map方法返回一个新数组 ,基于原数组返回一个一样长度的新数组 map映射非常适合
2.聚合的意义:把多个值聚合为一个元素,对数值数组元素求和 求积 等计算用聚合很适合,或者是把一个数组元素所有的值放入一个对象并且返回,用聚合很适合;
3.模板字符串和或运算符比字符串拼接和三元运算符更通俗易懂
下面是一个场景,几种方法的应用对比
其实在这种需求下,用map最适合
下面来上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 目标:将一个对象的部分属性,赋值给另一个数组的每个对象
// 初始化数据举例
// 这个是我们将要使用的对象,需要使用这个对象的部分属性
let oldObj={
aa:1,
ab:'haha',
pa1:'pa1',
pa2:'pa2',
pa3:'pa3',
pa4:'pa4',
pa5:'pa5',
pa6:'pa6',
}
// 这个是我们将要建立的数组的长度
let arrLength=6;
// 方法一 forEach
let arr=[];
Array.apply(null,{length:arrLength}).forEach((_,i) => {
let item = oldObj['pa'+(i+1)];
let object = {
id: i+1,
value: item?item:''
}
arr.push(object)
});
console.log('方法1');
console.log(arr);
// 方法二 map
let arr1 = Array.apply(null, { length: arrLength}).map((_, i) => ({
id: i + 1, value: oldObj['pa'+(i+1)] || ''
}))
console.log('方法2');
console.log(arr1);
// 方法三 reduce
let obj = Array.apply(null, { length: arrLength}).reduce((acc, _, i) => ({
...acc, [i + 1]: oldObj[`pa${i+1}`] || ''}), {})
console.log('方法3 reduce');
console.log(obj);
// 方法四 有问题,无法实现
let arr3=new Array(arrLength).fill({});
arr3.forEach((_,i)=>{
let item = oldObj['pa'+(i+1)];
_.id = (i+1);
_.value = item ? item : '';
console.log(_)
})
console.log('方法4');
console.log(arr3);
</script>
</body>
</html>