javascript
javascript函数式_如何以及为什么在现代JavaScript中使用函数式编程
javascript函數(shù)式
by PALAKOLLU SRI MANIKANTA
通過PALAKOLLU SRI MANIKANTA
In this article, you will get a deep understanding of functional programming and its benefits.
在本文中,您將對(duì)函數(shù)式編程及其好處有深入的了解。
函數(shù)式編程簡(jiǎn)介 (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.
函數(shù)式編程(FP)是計(jì)算機(jī)科學(xué)中的一種范例或模式。 一切都在FP中的功能的幫助下完成,而基本構(gòu)建塊僅是功能。
Programming languages that support purely functional programming are —
支持純函數(shù)式編程的編程語言是-
Some of the programming languages that support functional programming as well as other programming paradigms are —
一些支持函數(shù)式編程以及其他編程范例的編程語言是:
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.
顧名思義,函數(shù)就是這樣,大多數(shù)程序員都考慮數(shù)學(xué)函數(shù)。 FP并非如此。 這只是一種以簡(jiǎn)單有效的方式解決現(xiàn)實(shí)世界中復(fù)雜問題的抽象方法。
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.
在面向?qū)ο缶幊虝r(shí)代之前,軟件行業(yè)完全依賴于功能編程。 這種范例震撼了軟件行業(yè)數(shù)十年。 函數(shù)式編程存在一些問題,這就是為什么它們遷移到面向?qū)ο蟮姆独脑颉?FP的問題將在本文后面討論。
That is all about the introduction to Functional Programming. Now, first of all, we need to learn what is a function.
以上就是關(guān)于函數(shù)式編程的介紹。 現(xiàn)在,首先,我們需要學(xué)習(xí)什么是函數(shù)。
功能 (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 —
在揭示實(shí)際定義之前,我想解釋一下一種情況,以了解在哪里實(shí)際使用FP。 假設(shè)您正在編寫代碼以構(gòu)建應(yīng)用程序。 在開發(fā)過程中,您想在不同的地方重用幾行代碼(100)。 對(duì)于您的應(yīng)用程序,功能很有幫助。 我們可以在一處編寫函數(shù),并且可以從程序中的任何位置訪問這些函數(shù)。 函數(shù)式編程具有以下功能-
Let’s look at the actual definition of a function:
讓我們看一下函數(shù)的實(shí)際定義:
A Function is a specified block of code which is used to perform a specific task in the program.功能是指定的代碼塊,用于在程序中執(zhí)行特定任務(wù)。The most popular types of functions are —
最受歡迎的功能類型是-
一般功能 (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:
常規(guī)功能不過是程序員經(jīng)常用于執(zhí)行特定任務(wù)的功能。 在Javascript中聲明常規(guī)功能的語法為:
function functionName(parameters) { // code to be executed}function — It is a keyword which is necessary to declare a function.
function —這是聲明函數(shù)所必需的關(guān)鍵字。
functionName — It can be named based on the function work.
functionName —可以基于函數(shù)工作進(jìn)行命名。
parameters — We can pass any number of parameters to a function.
參數(shù)-我們可以將任意數(shù)量的參數(shù)傳遞給函數(shù)。
Declared functions are not executed immediately. They are “saved for later use”, and will be executed later, when they are invoked (called upon).聲明的函數(shù)不會(huì)立即執(zhí)行。 它們被“保存以備后用”,并且將在它們被調(diào)用時(shí)被執(zhí)行。We need to call the function when we want to execute that piece of code that is returned within a function.
當(dāng)我們想執(zhí)行一個(gè)函數(shù)中返回的那段代碼時(shí),我們需要調(diào)用該函數(shù)。
The general functions are classified as follows —
一般功能分類如下:
無參數(shù)函數(shù) (No-Argument Functions)
We don’t need to pass any arguments to the function.
我們不需要將任何參數(shù)傳遞給該函數(shù)。
// Function Declarationfunction sayHello(){ alert('Hello...!');}// Calling the functionsayHello()When we call the function to sayHello() it will produce the alert message as Hello.
當(dāng)我們將函數(shù)調(diào)用為sayHello()時(shí),它將生成警報(bào)消息,即Hello。
參數(shù)函數(shù) (Argument Functions)
In this type of functions, we will pass arguments to them.
在這類函數(shù)中,我們將參數(shù)傳遞給它們。
Example
例
// Declaring a Functionfunction add(num1, num2){ return num1 + num2;}// Function Callvar 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.
聲明函數(shù)(即(num1,num2))時(shí)傳遞的參數(shù)稱為形式參數(shù)。
The arguments that are passed while calling a function i.e (7, 11) are called as Actual Parameters.
調(diào)用函數(shù)(即(7,11))時(shí)傳遞的參數(shù)稱為實(shí)際參數(shù)。
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.
函數(shù)通常返回一些值,要返回該值,我們需要使用return關(guān)鍵字。 當(dāng)函數(shù)返回某個(gè)值時(shí),這意味著它不為我們輸出任何輸出,而只是返回最終輸出。 打印結(jié)果是我們的責(zé)任。 在上面的程序中,該函數(shù)返回值,并將該值傳遞給變量名'result'。 現(xiàn)在,該函數(shù)會(huì)將結(jié)果傳遞給“結(jié)果”變量。
Javascript函數(shù)的專長(zhǎng) (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.
如果傳遞的參數(shù)多于聲明的數(shù)字,則不會(huì)出現(xiàn)任何錯(cuò)誤。 但是在其他編程語言(例如Python,C,C ++,Java等)中,我們會(huì)收到錯(cuò)誤消息。 Javascript將根據(jù)其要求進(jìn)行考慮。
Example
例
// Calling the function with more number of arguments than the declared numbervar 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.
如果您傳遞的參數(shù)少于聲明的數(shù)量,那么我們也不會(huì)收到任何錯(cuò)誤。 但是我們無法預(yù)測(cè)程序的輸出,因?yàn)閷⒏鶕?jù)您的函數(shù)功能生成輸出。
可變參數(shù)函數(shù) (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函數(shù)的最大優(yōu)點(diǎn)是我們可以將任意數(shù)量的參數(shù)傳遞給該函數(shù)。 此功能可幫助開發(fā)人員以一致的方式更有效地工作。
Example
例
// Creating a function to calculate sum of all argument numbersfunction sumAll(){let sum = 0;for(let i=0;i<arguments.length;i++){ sum = sum + arguments[i];}return sum;}// Calling the sumAll functionsumAll();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.
這都是關(guān)于用于以簡(jiǎn)單方式執(zhí)行復(fù)雜任務(wù)的常規(guī)功能的。 現(xiàn)在讓我們討論一下ES6中引入的一些高級(jí)功能,稱為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.
箭頭函數(shù)表達(dá)式是常規(guī)函數(shù)表達(dá)式的緊湊語法替代方案。 它沒有對(duì)this , super , arguments或new.target關(guān)鍵字的綁定。 箭頭函數(shù)表達(dá)式不適合作為方法。 它們不能用作構(gòu)造函數(shù)。
One of the most loved features in Es6 are Arrow functions. This arrow function helps developers time and simplify function scope.Es6中最受歡迎的功能之一是Arrow功能。 此箭頭功能可幫助開發(fā)人員節(jié)省時(shí)間并簡(jiǎn)化功能范圍。The syntax for the arrow function is:
箭頭函數(shù)的語法為:
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.
創(chuàng)建箭頭功能向用戶說出歡迎信息。
// Creating a Welcome functionlet sayHello = () => { return 'Welcome to Javascript World...!';}// Calling the functionconsole.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.
在此示例中,我們將創(chuàng)建一個(gè)Arrow函數(shù),以生成作為參數(shù)傳遞的所有數(shù)字中的最大值。
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 functionconsole.log(maxNumber(1,2,4,3));Output:
輸出:
可變參數(shù)與箭頭函數(shù)的組合 (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
由于我們使用的是箭頭函數(shù),因此默認(rèn)情況下它不像常規(guī)函數(shù)那樣支持arguments數(shù)組。 我們有責(zé)任明確聲明它支持可變數(shù)量的參數(shù)
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 Functionconsole.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.
這就是我們?nèi)绾螌⒖勺償?shù)量的參數(shù)與箭頭函數(shù)結(jié)合在一起的方法。 現(xiàn)在讓我們討論JavaScript中的匿名函數(shù)。
匿名函數(shù) (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.
匿名函數(shù)就是沒有名稱的函數(shù)。 使用匿名函數(shù)的目的是執(zhí)行某個(gè)任務(wù),而不再需要對(duì)該任務(wù)進(jìn)行編程。 通常,匿名函數(shù)在運(yùn)行時(shí)動(dòng)態(tài)聲明。
Anonymous functions are called only once in a program.匿名函數(shù)在程序中僅被調(diào)用一次。Example:
例:
// Working with an Anonymous functionvar 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 scopeconsole.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.
這是匿名函數(shù)的概念。 我想我以簡(jiǎn)單的方式進(jìn)行了解釋。
高階函數(shù) (Higher Order Functions)
A higher-order function is a function that takes functions as an argument or that returns another function as a result.
高階函數(shù)是將函數(shù)作為參數(shù)或返回另一個(gè)函數(shù)的函數(shù)。
The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().
Javascript中高階函數(shù)的最佳示例是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 filterlet 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.
這是函數(shù)式編程中的關(guān)鍵主題之一。 函數(shù)直接或間接調(diào)用的過程稱為遞歸函數(shù)。 遞歸的概念在解決算法問題(如河內(nèi)塔,預(yù)訂購(gòu),后訂購(gòu),有序訂購(gòu)以及某些圖遍歷問題)中非常有用。
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
讓我們討論一個(gè)著名的例子:使用遞歸查找數(shù)字的階乘。 可以通過直接從程序中直接調(diào)用該函數(shù)來完成。 該程序的邏輯是
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 Recursionfunction factorial(num){ if(num == 0) return 1; else return num * factorial(num - 1);}// calling the functionconsole.log(factorial(3));console.log(factorial(7));console.log(factorial(0));Output
輸出量
函數(shù)式編程的特點(diǎn) (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語言的目標(biāo)都是模仿數(shù)學(xué)概念的使用。 但是,計(jì)算的基本過程在函數(shù)式編程中有所不同。 函數(shù)式編程的主要特點(diǎn)是:
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.
數(shù)據(jù)是不可變的:函數(shù)內(nèi)部存在的數(shù)據(jù)是不可變的。 在函數(shù)式編程中,我們可以輕松創(chuàng)建一個(gè)新的數(shù)據(jù)結(jié)構(gòu),但不能修改現(xiàn)有的數(shù)據(jù)結(jié)構(gòu)。
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.
可維護(hù)性:函數(shù)式編程為開發(fā)人員和程序員帶來了極大的可維護(hù)性。 我們不必?fù)?dān)心在給定功能之外意外進(jìn)行的更改。
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.
模塊化:這是函數(shù)式編程的最重要特征之一。 這有助于我們將大型項(xiàng)目分解為更簡(jiǎn)單的模塊。 這些模塊可以分別進(jìn)行測(cè)試,從而幫助您減少在單元測(cè)試和調(diào)試上花費(fèi)的時(shí)間。
函數(shù)式編程的優(yōu)點(diǎn) (Advantages Of Functional Programming)
函數(shù)式編程的缺點(diǎn) (Disadvantages Of Functional Programming)
結(jié)論 (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.
對(duì)于某些人來說,這可能是一個(gè)全新的編程范例。 希望您在編程過程中能有機(jī)會(huì)。 我認(rèn)為您會(huì)發(fā)現(xiàn)程序更易于閱讀和調(diào)試。
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.
對(duì)于您而言,此函數(shù)式編程概念可能會(huì)有些棘手和困難。 即使您是初學(xué)者,也將最終變得更容易。 然后,您可以享受功能編程的功能。
If you liked this article please share with your friends.
如果您喜歡這篇文章,請(qǐng)與您的朋友分享。
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.
您好忙碌的人們,希望您在閱讀這篇文章時(shí)玩得開心,也希望您在這里學(xué)到了很多東西! 這是我分享我所學(xué)內(nèi)容的嘗試。
I hope you saw something useful for you here. And see you next time!
希望您在這里看到了對(duì)您有用的東西。 下次見!
Have fun! Keep learning new things and coding to solve problems.
玩得開心! 不斷學(xué)習(xí)新事物并編寫編碼以解決問題。
Check out My Twitter, Github, and Facebook.
查看我的Twitter , Github和Facebook 。
翻譯自: https://www.freecodecamp.org/news/how-and-why-to-use-functional-programming-in-modern-javascript-fda2df86ad1b/
javascript函數(shù)式
總結(jié)
以上是生活随笔為你收集整理的javascript函数式_如何以及为什么在现代JavaScript中使用函数式编程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己结冥婚是怎么回事
- 下一篇: 做梦梦到捡到狗是什么意思