javascript函数式_如何以及为什么在现代JavaScript中使用函数式编程

javascript函数式

by PALAKOLLU SRI MANIKANTA

通过PALAKOLLU SRI MANIKANTA

In this article, you will get a deep understanding of functional programming and its benefits.

在本文中,您将对函数式编程及其好处有深入的了解。

函数式编程简介 (Introduction To Functional Programming)

Functional programming (FP) is a type of paradigm or pattern in computer science. Everything is done with the help of functions in FP and the basic building blocks are functions only.

函数式编程(FP)是计算机科学中的一种范例或模式。 一切都在FP中的功能的帮助下完成,而基本构建块仅是功能。

Programming languages that support purely functional programming are —

支持纯函数式编程的编程语言是-

  1. Haskell

    哈斯克尔
  2. Closure

    关闭
  3. Scala

    Scala
  4. SQL

    SQL

Some of the programming languages that support functional programming as well as other programming paradigms are —

一些支持函数式编程以及其他编程范例的编程语言是:

  1. Python

    Python
  2. Javascript

    Java脚本
  3. C++

    C ++
  4. Ruby

    Ruby

Since the name says functional, most of the programmers think about Mathematical functions. That is not the case with FP. It is just an abstraction to solve real-world complex problems in an easy and effective manner.

顾名思义,函数就是这样,大多数程序员都考虑数学函数。 FP并非如此。 这只是一种以简单有效的方式解决现实世界中复杂问题的抽象方法。

Before the Object-Oriented programming Era, the software industry completely depended on functional programming. This paradigm rocked the software industry for a couple of decades. There are some issues with functional programming, and that’s why they moved to Object-Oriented paradigm. The issues with FP will be discussed later in this article.

在面向对象编程时代之前,软件行业完全依赖于功能编程。 这种范例震撼了软件行业数十年。 函数式编程存在一些问题,这就是为什么它们迁移到面向对象的范例的原因。 FP的问题将在本文后面讨论。

That is all about the introduction to Functional Programming. Now, first of all, we need to learn what is a function.

以上就是关于函数式编程的介绍。 现在,首先,我们需要学习什么是函数。

功能 (Functions)

Before revealing the actual definition, I want to explain a situation to know where to actually use FP. Suppose you are writing code to build an application. In your development journey, you want to reuse the code of a few lines (100) at different places. For your Application, functions are helpful. We can write functions at one place and we will be able to access those functions from anywhere in the program. Functional programming has the following features —

在揭示实际定义之前,我想解释一下一种情况,以了解在哪里实际使用FP。 假设您正在编写代码以构建应用程序。 在开发过程中,您想在不同的地方重用几行代码(100)。 对于您的应用程序,功能很有帮助。 我们可以在一处编写函数,并且可以从程序中的任何位置访问这些函数。 函数式编程具有以下功能-

  1. Reduces code redundancy.

    减少代码冗余。
  2. Improves modularity.

    改善模块化。
  3. Helps us to solve complex problems.

    帮助我们解决复杂的问题。
  4. Increases maintainability.

    提高可维护性。

Let’s look at the actual definition of a function:

让我们看一下函数的实际定义:

A Function is a specified block of code which is used to perform a specific task in the program.
功能是指定的代码块,用于在程序中执行特定任务。

The most popular types of functions are —

最受欢迎的功能类型是-

  1. General Functions

    一般功能
  2. Arrow Functions

    箭头功能
  3. Anonymous Functions

    匿名函数

一般功能 (General Functions)

General functions are nothing but the functions that are quite often used by the programmer to perform a specific task. The syntax to declare a general function in Javascript is:

常规功能不过是程序员经常用于执行特定任务的功能。 在Javascript中声明常规功能的语法为:

function functionName(parameters) {  // code to be executed}

function — It is a keyword which is necessary to declare a function.

function —这是声明函数所必需的关键字。

functionName — It can be named based on the function work.

functionName —可以基于函数工作进行命名。

parameters — We can pass any number of parameters to a function.

参数-我们可以将任意数量的参数传递给函数。

Declared functions are not executed immediately. They are “saved for later use”, and will be executed later, when they are invoked (called upon).
声明的函数不会立即执行。 它们被“保存以备后用”,并且将在它们被调用时被执行。

We need to call the function when we want to execute that piece of code that is returned within a function.

当我们想执行一个函数中返回的那段代码时,我们需要调用该函数。

The general functions are classified as follows —

一般功能分类如下:

无参数函数 (No-Argument Functions)

We don’t need to pass any arguments to the function.

我们不需要将任何参数传递给该函数。

// Function Declaration
function sayHello(){   alert('Hello...!');}
// Calling the functionsayHello()

When we call the function to sayHello() it will produce the alert message as Hello.

当我们将函数调用为sayHello()时,它将生成警报消息,即Hello。

参数函数 (Argument Functions)

In this type of functions, we will pass arguments to them.

在这类函数中,我们将参数传递给它们。

Example

// Declaring a Function
function add(num1, num2){   return num1 + num2;}
// Function Call
var result = add(7, 11);
console.log(result);

The arguments that are passed while declaring a function i.e (num1, num2) are called as Formal Parameters.

声明函数(即(num1,num2))时传递的参数称为形式参数。

The arguments that are passed while calling a function i.e (7, 11) are called as Actual Parameters.

调用函数(即(7,11))时传递的参数称为实际参数。

A Function usually returns some value, and to return that value we need to use return keyword. When a function is returning some value it means it doesn’t print any output for us, it just returns the final output. It is our responsibility to print that result. In the above program, the function is returning the value and I’m passing that value to a variable name ‘result’. Now the function will pass the result to the ‘result’ variable.

函数通常返回一些值,要返回该值,我们需要使用return关键字。 当函数返回某个值时,这意味着它不为我们输出任何输出,而只是返回最终输出。 打印结果是我们的责任。 在上面的程序中,该函数返回值,并将该值传递给变量名'result'。 现在,该函数会将结果传递给“结果”变量。

Javascript函数的专长 (The speciality of Javascript Functions)

If you pass more arguments than the declared number, then you will not get any error. But in other programming languages like Python, C, C++, Java, etc… we will get an error. Javascript will consider based on their requirements.

如果传递的参数多于声明的数字,则不会出现任何错误。 但是在其他编程语言(例如Python,C,C ++,Java等)中,我们会收到错误消息。 Javascript将根据其要求进行考虑。

Example

// Calling the function with more number of arguments than the declared number
var result1 = add(2, 4, 6);console.log(result1);
var result2 = add(2);console.log(result2);

Output

输出量

If you pass fewer arguments than the declared number, then also we will not get any error. But we can’t predict the output for the program because, based on your function functionality, the output will be produced.

如果您传递的参数少于声明的数量,那么我们也不会收到任何错误。 但是我们无法预测程序的输出,因为将根据您的函数功能生成输出。

可变参数函数 (Variable Argument Function)

The greatest advantage of Javascript functions is we can pass any number of arguments to the function. This feature helps developers to work more effectively in a consistent manner.

Javascript函数的最大优点是我们可以将任意数量的参数传递给该函数。 此功能可帮助开发人员以一致的方式更有效地工作。

Example

// Creating a function to calculate sum of all argument numbers
function sumAll(){
let sum = 0;
for(let i=0;i<arguments.length;i++){      sum = sum + arguments[i];}
return sum;
}
// Calling the sumAll function
sumAll();
sumAll(1,2,3,12,134,3234,4233,12,3243);

Output

输出量

This is all about general functions that are used to perform our complex task in a simple manner. Now let’s discuss some advanced functions introduced in ES6 called Arrow Functions.

这都是关于用于以简单方式执行复杂任务的常规功能的。 现在让我们讨论一下ES6中引入的一些高级功能,称为Arrow Functions

箭头功能 (Arrow Functions)

An arrow function expression is a syntactically compact alternative to a regular function expression. It doesn’t have its own bindings to the this, super, arguments or new.target keywords. Arrow function expressions are ill-suited as methods. They cannot be used as constructors.

箭头函数表达式是常规函数表达式的紧凑语法替代方案。 它没有对thissuperargumentsnew.target关键字的绑定。 箭头函数表达式不适合作为方法。 它们不能用作构造函数。

One of the most loved features in Es6 are Arrow functions. This arrow function helps developers time and simplify function scope.
Es6中最受欢迎的功能之一是Arrow功能。 此箭头功能可帮助开发人员节省时间并简化功能范围。

The syntax for the arrow function is:

箭头函数的语法为:

const functionName = (parameters) => {  // code to be executed}
(OR)
var functionName = (parameters) => {  // code to be executed}
(OR)
let functionName = (parameters) => {  // code to be executed}

箭头功能示例 (Examples for Arrow Functions)

Eg 1

例如1

Creating an Arrow function to say a welcome message to the users.

创建箭头功能向用户说出欢迎信息。

// Creating a Welcome function
let sayHello = () => {   return 'Welcome to Javascript World...!';}
// Calling the function
console.log(sayHello())

Output

输出量

Eg 2

例如2

In this example, we are creating an Arrow function to generate the greatest of all numbers that are passed as an argument.

在此示例中,我们将创建一个Arrow函数,以生成作为参数传递的所有数字中的最大值。

let maxNumber = (a,b,c,d) => {
if(a > b && a > c && a > d)       return a;   else if(b > a && b > c && b>d)       return b;   else if(c > a && c > b && c > d)       return c;   else       return d;}
// Calling the function
console.log(maxNumber(1,2,4,3));

Output:

输出:

可变参数与箭头函数的组合 (Combination of Variable Arguments with Arrow Functions)

Since we are working with an arrow function, it doesn’t support the arguments array by default like general function. It is our responsibility to declare explicitly that it supports the variable number of arguments

由于我们使用的是箭头函数,因此默认情况下它不像常规函数那样支持arguments数组。 我们有责任明确声明它支持可变数量的参数

Eg 3

例如3

let varArgSum = (...args) => {   let sum = 0;
for(let i=0;i<args.length;i++){      sum = sum + args[i];}
return sum;
}
// Calling the Function
console.log(varArgSum());
console.log(varArgSum(1,2,3,4,5,6,7,8,9,10));

Output

输出量

This is how we can combine a variable number of arguments with arrow functions. Now let’s discuss Anonymous functions in JavaScript.

这就是我们如何将可变数量的参数与箭头函数结合在一起的方法。 现在让我们讨论JavaScript中的匿名函数。

匿名函数 (Anonymous Functions)

An anonymous function is simply a function with no name. The purpose of using anonymous function is to perform a certain task and that task is no longer required to program. Generally, anonymous functions are declared dynamically at run time.

匿名函数就是没有名称的函数。 使用匿名函数的目的是执行某个任务,而不再需要对该任务进行编程。 通常,匿名函数在运行时动态声明。

Anonymous functions are called only once in a program.
匿名函数在程序中仅被调用一次。

Example:

例:

// Working with an Anonymous function
var a = 10;  // Global Scope Variable.
// creating a function(function() {
console.log("welcome to the world of Anonymous function");
var b = 20;  // b is a local scope variable.
var c = a+b; // c is a local scope variable    //a can be used because it is in the global scope
console.log("Addition of two numbers value is: "+c);})();

Output

输出量

This is the concept of anonymous functions. I think I explained it in a simple and easy way.

这是匿名函数的概念。 我想我以简单的方式进行了解释。

高阶函数 (Higher Order Functions)

A higher-order function is a function that takes functions as an argument or that returns another function as a result.

高阶函数是将函数作为参数或返回另一个函数的函数。

The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().

Javascript中高阶函数的最佳示例是Array.map(),Array.reduce(),Array.filter()。

Example 1: Array.map()

示例1:Array.map()

// working with Array.map()
let myNumberArray = [4,9,16,25,36,49];
let mySquareRootArray = myNumberArray.map(Math.sqrt);
console.log(mySquareRootArray);

Output

输出量

Example 2: Array.reduce()

示例2:Array.reduce()

// working with Array.reduce()
let someRandomNumbers = [24,1,23,78,93,47,86];
function getSum(total, num){  return total + num;}
let newReducedResult = someRandomNumbers.reduce(getSum);
console.log(newReducedResult);

Output

输出量

Example 3: Array.filter()

示例3:Array.filter()

// Working with array filter
let ages = [12,24,43,57,18,90,43,36,92,11,3,4,8,9,9,15,16,14];
function rightToVote(age){   return age >= 18;}
let votersArray = ages.filter(rightToVote);
console.log(votersArray);

Output

输出量

递归 (Recursion)

This is one of the key topics in functional programming. The process in which a function calls directly or indirectly is called a recursive function. This concept of recursion is quite useful in solving algorithmic problems like the Towers of Hanoi, Pre-Order, Post-Order, In-Order, and some graph traversal problems.

这是函数式编程中的关键主题之一。 函数直接或间接调用的过程称为递归函数。 递归的概念在解决算法问题(如河内塔,预订购,后订购,有序订购以及某些图遍历问题)中非常有用。

Example

Let’s discuss a famous example: finding the factorial of a number using recursion. This can be done by calling the function directly from the program repeatedly. The logic for the program is

让我们讨论一个著名的例子:使用递归查找数字的阶乘。 可以通过直接从程序中直接调用该函数来完成。 该程序的逻辑是

factorial(n) = factorial(n) * factorial(n - 1) * factorial(n - 2) * factorial(n - 3) * ….. * factorial(n - n);
因子(n)=因子(n)*因子(n-1)*因子(n-2)*因子(n-3)*….. *因子(n-n);
// Finding the factorial of a number using Recursion
function factorial(num){  if(num == 0)        return 1;  else        return num * factorial(num - 1);
}
// calling the function
console.log(factorial(3));
console.log(factorial(7));
console.log(factorial(0));

Output

输出量

函数式编程的特点 (Characteristics Of Functional Programming)

The objective of any FP language is to mimic the use of mathematical concepts. However, the basic process of computation is different in functional programming. The major characteristics of functional programming are:

任何FP语言的目标都是模仿数学概念的使用。 但是,计算的基本过程在函数式编程中有所不同。 函数式编程的主要特点是:

Data is immutable: The data which is present inside the functions are immutable. In Functional programming, we can easily create a new Data structure but we can’t modify the existing one.

数据是不可变的:函数内部存在的数据是不可变的。 在函数式编程中,我们可以轻松创建一个新的数据结构,但不能修改现有的数据结构。

Maintainability: Functional programming produces great maintainability for developers and programmers. We don’t need to worry about changes that are accidentally done outside the given function.

可维护性:函数式编程为开发人员和程序员带来了极大的可维护性。 我们不必担心在给定功能之外意外进行的更改。

Modularity: This is one of the most important characteristics of functional programming. This helps us to break down a large project into simpler modules. These modules can be tested separately which helps you to reduce the time spent on unit testing and debugging.

模块化:这是函数式编程的最重要特征之一。 这有助于我们将大型项目分解为更简单的模块。 这些模块可以分别进行测试,从而帮助您减少在单元测试和调试上花费的时间。

函数式编程的优点 (Advantages Of Functional Programming)

  1. It helps us to solve problems effectively in a simpler way.

    它帮助我们以更简单的方式有效地解决问题。
  2. It improves modularity.

    它提高了模块化。
  3. It allows us to implement lambda calculus in our program to solve complex problems.

    它允许我们在程序中实现lambda演算以解决复杂问题。
  4. Some programming languages support nested functions which improve maintainability of the code.

    某些编程语言支持嵌套函数,这些函数可提高代码的可维护性。
  5. It reduces complex problems into simple pieces.

    它将复杂的问题简化为简单的部分。
  6. It improves the productivity of the developer.

    它提高了显影剂的生产率。
  7. It helps us to debug the code quickly.

    它有助于我们快速调试代码。

函数式编程的缺点 (Disadvantages Of Functional Programming)

  1. For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers.

    对于初学者来说,很难理解。 因此,对于新程序员而言,这不是一种适合初学者的范例方法。
  2. Maintainance is difficult during the coding phase when the project size is large.

    当项目规模较大时,在编码阶段很难维护。
  3. Reusability in Functional programming is a tricky task for developers.

    对于开发人员而言,函数式编程中的可重用性是一项艰巨的任务。

结论 (Conclusion)

For some, it might be a completely new programming paradigm. I hope you will give it a chance in your programming journey. I think you’ll find your programs easier to read and debug.

对于某些人来说,这可能是一个全新的编程范例。 希望您在编程过程中能有机会。 我认为您会发现程序更易于阅读和调试。

This Functional programming concept might be tricky and tough for you. Even if you are a beginner, it will eventually become easier. Then you can enjoy the features of functional programming.

对于您而言,此函数式编程概念可能会有些棘手和困难。 即使您是初学者,也将最终变得更容易。 然后,您可以享受功能编程的功能。

If you liked this article please share with your friends.

如果您喜欢这篇文章,请与您的朋友分享。

Hello busy people, I hope you had fun reading this post, and I hope you learned a lot here! This was my attempt to share what I’m learning.

您好忙碌的人们,希望您在阅读这篇文章时玩得开心,也希望您在这里学到了很多东西! 这是我分享我所学内容的尝试。

I hope you saw something useful for you here. And see you next time!

希望您在这里看到了对您有用的东西。 下次见!

Have fun! Keep learning new things and coding to solve problems.

玩得开心! 不断学习新事物并编写编码以解决问题。

Check out My Twitter, Github, and Facebook.

查看我的TwitterGithubFacebook

翻译自: https://www.freecodecamp.org/news/how-and-why-to-use-functional-programming-in-modern-javascript-fda2df86ad1b/

javascript函数式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值