for 循环不是目的,map 映射更有意义!【FP探究】

简介: 在 JavaScript 中,由于 Function 本质也是对象(这与 Haskell 中【函数的本质是值】思路一致),所以我们可以把 Function 作为参数来进行传递!

image.png

楔子



在 JavaScript 中,由于 Function 本质也是对象(这与 Haskell 中【函数的本质是值】思路一致),所以我们可以把 Function 作为参数来进行传递


例🌰:

function sayHi() {
  console.log("Hi");
}
function sayBye() {
  console.log("Bye");
}
function greet(type, sayHi, sayBye) {
    type === 1 ? sayHi() : sayBye()
}
greet(1, sayHi, sayBye); // Hi


又得讲这个老生常谈的定义:如果一个函数“接收函数作为参数”或“返回函数作为输出”,那么这个函数被称作“高阶函数”


本篇要谈的是:高阶函数中的 mapfilterreduce 是【如何实践】的,我愿称之为:高阶映射!!


先别觉得这东西陌生,其实咱们天天都见!!

例🌰:

[1,2,3].map(item => item*2)


实践



Talk is cheap. Show me the code.


以下有 4 组代码,每组的 2 个代码片段实现目标一致,但实现方式有异,感受感受,你更喜欢哪个?💖


第 1 组:

1️⃣

const arr1 = [1, 2, 3];
const arr2 = [];
for(let i = 0; i < arr1.length; i++) {
  arr2.push(arr1[i] * 2);
}
console.log(arr2); // [ 2, 4, 6 ]


2️⃣

const arr1 = [1, 2, 3];
const arr2 = arr1.map(item => item * 2);
console.log(arr2);  // [ 2, 4, 6 ]


第 2 组:

1️⃣

const birthYear = [1975, 1997, 2002, 1995, 1985];
const ages = [];
for(let i = 0; i < birthYear.length; i++) {
  let age = 2018 - birthYear[i];
  ages.push(age);
}
console.log(ages); // [ 43, 21, 16, 23, 33 ]


2️⃣

const birthYear = [1975, 1997, 2002, 1995, 1985];
const ages = birthYear.map(year => 2018 - year);
console.log(ages); // [ 43, 21, 16, 23, 33 ]


第 3 组:

1️⃣

const persons = [
  { name: 'Peter', age: 16 },
  { name: 'Mark', age: 18 },
  { name: 'John', age: 27 },
  { name: 'Jane', age: 14 },
  { name: 'Tony', age: 24},
];
const fullAge = [];
for(let i = 0; i < persons.length; i++) {
  if(persons[i].age >= 18) {
    fullAge.push(persons[i]);
  }
}
console.log(fullAge);


2️⃣

const persons = [
  { name: 'Peter', age: 16 },
  { name: 'Mark', age: 18 },
  { name: 'John', age: 27 },
  { name: 'Jane', age: 14 },
  { name: 'Tony', age: 24},
];
const fullAge = persons.filter(person => person.age >= 18);
console.log(fullAge);


第 4 组:

1️⃣

const arr = [5, 7, 1, 8, 4];
let sum = 0;
for(let i = 0; i < arr.length; i++) {
  sum = sum + arr[i];
}
console.log(sum); // 25


2️⃣

const arr = [5, 7, 1, 8, 4];
const sum = arr.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
});
console.log(sum); // 25


更喜欢哪个?有答案了吗?

image.png


每组的代码片段 2️⃣ 就是map/filter/reduce高阶函数的应用,没有别的说的,就是更加简洁易读


手写



实际上,map/filter/reduce 也是基于 for 循环封装来的,所以我们也能自己实现一套相同的 高阶映射 🚀;


  • map1
Array.prototype.map1 = function(fn) {
    let newArr = [];
    for (let i = 0; i < this.length; i++) {
        newArr.push(fn(this[i]))
    };
    return newArr;
}
console.log([1,2,3].map1(item => item*2)) // [2,4,6]


  • filter1
Array.prototype.filter1 = function (fn) {
  let newArr=[];
  for(let i=0;i<this.length;i++){
      fn(this[i]) && newArr.push(this[i]);
  }
  return newArr;
};
console.log([1,2,3].filter1(item => item>2)) // [3]


  • reduce1
Array.prototype.reduce1 = function (reducer,initVal) {
    for(let i=0;i<this.length;i++){
        initVal =reducer(initVal,this[i],i,this);
    }
    return initVal
};
console.log([1,2,3].reduce1((a,b)=>a+b,0)) // 6


如果你不想直接挂在原型链上🛸:

  • mapForEach
function mapForEach(arr, fn) {
  const newArray = [];
  for(let i = 0; i < arr.length; i++) {
    newArray.push(
      fn(arr[i])
    );
  }
  return newArray;
}
mapForEach([1,2,3],item=>item*2) // [2,4,6]


  • filterForEach
function filterForEach(arr, fn) {
  const newArray = [];
  for(let i = 0; i < arr.length; i++) {
     fn(arr[i]) && newArray.push(arr[i]);
  }
  return newArray;
}
filterForEach([1,2,3],item=>item>2) // [3]


  • reduceForEach
function reduceForEach(arr,reducer,initVal) {
  const newArray = [];
  for(let i = 0; i < arr.length; i++) {
      initVal =reducer(initVal,arr[i],i,arr);
  }
  return initVal;
}
reduceForEach([1,2,3],(a,b)=>a+b,0) // 6


这里本瓜有个小疑惑,在 ES6 之前,有没有一个库做过这样的封装❓


小结



本篇虽基础,但很重要


对一些惯用写法的审视、改变,会产生一些奇妙的思路~ 稀松平常的 map 映射能做的比想象中的要多得多!


for 循环遍历只是操作性的手段,不是目的!而封装过后的 map 映射有了更易读的意义,映射关系(输入、输出)也是函数式编程之核心!


YY一下:既然 map 这类函数都是从 for 循环封装来的,如果你能封装一个基于 for 循环的另一种特别实用的高阶映射或者其它高阶函数,是不是意味着:有朝一日有可能被纳入 JS 版本标准 API 中?🐶🐶🐶


或许:先意识到我们每天都在使用的高阶函数,刻意的去使用、训练,然后能举一反三,才能做上面的想象吧~~~

以上。


您的点赞、评论、关注是本瓜最大的鼓励 O(∩_∩)O👍👍👍


相关文章
go语言中遍历映射(map)
go语言中遍历映射(map)
439 8
|
JavaScript 前端开发 定位技术
JavaScript 中如何代理 Set(集合) 和 Map(映射)
JavaScript 中如何代理 Set(集合) 和 Map(映射)
364 0
|
存储 JavaScript 前端开发
for...of循环在遍历Set和Map时的注意事项有哪些?
for...of循环在遍历Set和Map时的注意事项有哪些?
848 156
|
10月前
|
存储 Java Go
【Golang】(3)条件判断与循环?切片和数组的关系?映射表与Map?三组关系傻傻分不清?本文带你了解基本的复杂类型与执行判断语句
在Go中,条件控制语句总共有三种if、switch、select。循环只有for,不过for可以充当while使用。如果想要了解这些知识点,初学者进入文章中来感受吧!
327 2
|
前端开发 程序员
【面试题】在循环 for、for-in、forEach、for-of 、map中改变item的值,会发生什么?
【面试题】在循环 for、for-in、forEach、for-of 、map中改变item的值,会发生什么?
258 0
go语言for遍历映射(map)
go语言for遍历映射(map)
626 12
|
存储 Go
go语言 遍历映射(map)
go语言 遍历映射(map)
499 2
|
人工智能 算法 大数据
算法金 | 推导式、生成器、向量化、map、filter、reduce、itertools,再见 for 循环
这篇内容介绍了编程中避免使用 for 循环的一些方法,特别是针对 Python 语言。它强调了 for 循环在处理大数据或复杂逻辑时可能导致的性能、可读性和复杂度问题。
410 6
算法金 | 推导式、生成器、向量化、map、filter、reduce、itertools,再见 for 循环
|
Go
Golang语言之映射(map)快速入门篇
这篇文章是关于Go语言中映射(map)的快速入门教程,涵盖了map的定义、创建方式、基本操作如增删改查、遍历、嵌套map的使用以及相关练习题。
428 5
|
存储 算法 C++
C++一分钟之-扁平化映射与unordered_map
【7月更文挑战第5天】C++的STL `unordered_map`是键值对的快速查找容器,基于哈希表。常见问题包括哈希函数选择、键类型限制、内存管理和迭代顺序不确定性。要避免问题,需优化哈希函数,确保自定义类型支持哈希和比较操作,合理管理内存,不依赖迭代顺序。提供的代码示例展示了如何为自定义类型定义哈希函数并操作`unordered_map`。正确使用能提升代码效率。
485 0
C++一分钟之-扁平化映射与unordered_map