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 —
支持純函數式編程的編程語言是-
- Haskell 哈斯克爾
- Closure 關閉
- Scala Scala
- SQL SQL
Some of the programming languages that support functional programming as well as other programming paradigms are —
一些支持函數式編程以及其他編程范例的編程語言是:
- Python Python
- Javascript Java腳本
- C++ C ++
- 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)。 對于您的應用程序,功能很有幫助。 我們可以在一處編寫函數,并且可以從程序中的任何位置訪問這些函數。 函數式編程具有以下功能-
- Reduces code redundancy. 減少代碼冗余。
- Improves modularity. 改善模塊化。
- Helps us to solve complex problems. 幫助我們解決復雜的問題。
- 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 —
最受歡迎的功能類型是-
- General Functions 一般功能
- Arrow Functions 箭頭功能
- 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.
箭頭函數表達式是常規函數表達式的緊湊語法替代方案。 它沒有對this , super , arguments或new.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)
- It helps us to solve problems effectively in a simpler way. 它幫助我們以更簡單的方式有效地解決問題。
- It improves modularity. 它提高了模塊化。
- It allows us to implement lambda calculus in our program to solve complex problems. 它允許我們在程序中實現lambda演算以解決復雜問題。
- Some programming languages support nested functions which improve maintainability of the code. 某些編程語言支持嵌套函數,這些函數可提高代碼的可維護性。
- It reduces complex problems into simple pieces. 它將復雜的問題簡化為簡單的部分。
- It improves the productivity of the developer. 它提高了顯影劑的生產率。
- It helps us to debug the code quickly. 它有助于我們快速調試代碼。
函數式編程的缺點 (Disadvantages Of Functional Programming)
- For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers. 對于初學者來說,很難理解。 因此,對于新程序員而言,這不是一種適合初學者的范例方法。
- Maintainance is difficult during the coding phase when the project size is large. 當項目規模較大時,在編碼階段很難維護。
- 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.
查看我的Twitter , Github和Facebook 。
翻譯自: https://www.freecodecamp.org/news/how-and-why-to-use-functional-programming-in-modern-javascript-fda2df86ad1b/
javascript函數式