”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > ESnd 箭头函数综合指南

ESnd 箭头函数综合指南

发布于2024-11-06
浏览:444

A Comprehensive Guide to ESnd Arrow Functions

ES6简介

ECMAScript 2015,也称为 ES6 (ECMAScript 6),是对 JavaScript 的重大更新,引入了新的语法和功能,使编码更高效、更易于管理。 JavaScript 是用于 Web 开发的最流行的编程语言之一,ES6 的改进大大增强了其功能。

本指南将涵盖 ES6 中引入的重要功能,特别关注 箭头函数,一种强大的新函数编写方式。

ES6 的主要特性

1. let 和 const

ES6引入了两种新的变量声明方式:let和const。

  • let:声明块作用域变量,这意味着该变量仅在声明它的块内可用。

     let x = 10;
     if (true) {
       let x = 2;
       console.log(x); // 2 (inside block)
     }
     console.log(x); // 10 (outside block)
    
  • const:声明一个不能重新赋值的常量变量。然而,这并不会使变量不可变——使用 const 声明的对象仍然可以更改其属性。

     const y = 10;
     y = 5; // Error: Assignment to constant variable.
    
     const person = { name: "John", age: 30 };
     person.age = 31; // This is allowed.
    

2. 箭头函数

ES6 最受关注的功能之一是箭头函数。它为编写函数提供了更短、更简洁的语法。

#### 语法比较:

传统函数(ES5):

   var add = function(x, y) {
     return x   y;
   };

箭头函数 (ES6):

   const add = (x, y) => x   y;

箭头函数的不同之处如下:

  • 更短的语法:不需要写function关键字,如果函数只有一条语句,可以省略大括号{}。
  • 隐式返回:如果函数只包含一个表达式,则自动返回该表达式的结果。
  • 没有 this 绑定:箭头函数没有自己的 this,使得它们不适合对象方法。

单线箭头函数示例:

   const multiply = (a, b) => a * b;
   console.log(multiply(4, 5)); // 20

箭头函数也可以不带参数使用:

   const greet = () => "Hello, World!";
   console.log(greet()); // "Hello, World!"

对于多行函数,需要大括号{},并且返回语句必须显式:

   const sum = (a, b) => {
     let result = a   b;
     return result;
   };

箭头函数和 this
一个重要的区别是箭头函数中的行为方式。与传统函数不同,箭头函数不绑定自己的 this — 它们从周围的上下文继承 this。

   const person = {
     name: "John",
     sayName: function() {
       setTimeout(() => {
         console.log(this.name);
       }, 1000);
     }
   };
   person.sayName(); // "John"

在上面的示例中,setTimeout 中的箭头函数从 sayName 方法继承了 this,它正确引用了 person 对象。

3. 解构赋值

解构允许我们从数组或对象中提取值,并以更简洁的方式将它们分配给变量。

对象解构:

   const person = { name: "John", age: 30 };
   const { name, age } = person;
   console.log(name); // "John"
   console.log(age);  // 30

数组解构:

   const fruits = ["Apple", "Banana", "Orange"];
   const [first, second] = fruits;
   console.log(first);  // "Apple"
   console.log(second); // "Banana"

4. 展开和休息运算符 (...)

... 运算符可用于将数组展开为单个元素或将多个元素收集到一个数组中。

  • Spread:将数组扩展为单个元素。

     const numbers = [1, 2, 3];
     const newNumbers = [...numbers, 4, 5];
     console.log(newNumbers); // [1, 2, 3, 4, 5]
    
  • Rest:将多个参数收集到一个数组中。

     function sum(...args) {
       return args.reduce((acc, curr) => acc   curr);
     }
     console.log(sum(1, 2, 3, 4)); // 10
    

5. 承诺

Promises 用于处理 JavaScript 中的异步操作。 Promise 代表了一个可能现在、将来或永远不可用的值。

例子:

   const myPromise = new Promise((resolve, reject) => {
     setTimeout(() => {
       resolve("Success!");
     }, 1000);
   });

   myPromise.then(result => {
     console.log(result); // "Success!" after 1 second
   });

在此示例中,promise 在 1 秒后解析,then() 方法处理解析后的值。

6. 默认参数

在ES6中,可以为函数参数设置默认值。当未提供或未定义参数时,这很有用。

例子:

   function greet(name = "Guest") {
     return `Hello, ${name}!`;
   }
   console.log(greet());       // "Hello, Guest!"
   console.log(greet("John")); // "Hello, John!"

7. 字符串方法(包括()、startsWith()、endsWith())

新方法已添加到字符串中以使常见任务变得更容易:

  • includes():检查字符串是否包含指定值。

     let str = "Hello world!";
     console.log(str.includes("world")); // true
    
  • startsWith():检查字符串是否以指定值开头。

     console.log(str.startsWith("Hello")); // true
    
  • endsWith():检查字符串是否以指定值结尾。

     console.log(str.endsWith("!")); // true
    

8. 数组方法 (find(), findIndex(), from())

ES6 引入了处理数组的新方法:

  • find():返回第一个满足条件的元素。

     const numbers = [5, 12, 8, 130, 44];
     const found = numbers.find(num => num > 10);
     console.log(found); // 12
    
  • findIndex():返回第一个满足条件的元素的索引。

     const index = numbers.findIndex(num => num > 10);
     console.log(index); // 1 (position of 12 in the array)
    

9. 课程

ES6 向 JavaScript 引入了类,它们是 JavaScript 现有的基于原型的继承的语法糖。类允许更清晰、更易于理解的面向对象编程。

例子:

   class Car {
     constructor(brand, year) {
       this.brand = brand;
       this.year = year;
     }

     displayInfo() {
       return `${this.brand} from ${this.year}`;
     }
   }

   const myCar = new Car("Toyota", 2020);
   console.log(myCar.displayInfo()); // "Toyota from 2020"

结论

ES6 改变了 JavaScript,使其更高效、更易于使用。 箭头函数的引入简化了函数语法,而解构promisesclasses扩展运算符等新功能 允许开发人员编写更清晰、更具表现力的代码。无论您是初学者还是高级开发人员,了解这些 ES6 功能对于编写现代 JavaScript 至关重要。

通过掌握这些概念,您将能够更好地应对现实世界的编码挑战并构建高效、可扩展的 Web 应用程序。

跟进 GitHub 上的 Arrow Functions 项目

参考

  • https://www.w3schools.com/js/js_es6.asp
  • https://towardsdatascience.com/javascript-es6-iterables-and-iterators-de18b54f4d4
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements
版本声明 本文转载于:https://dev.to/tobidelly/a-comprehensive-guide-to-es6-and-arrow-functions-k13?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Spark DataFrame添加常量列的妙招
    Spark DataFrame添加常量列的妙招
    在Spark Dataframe ,将常数列添加到Spark DataFrame,该列具有适用于所有行的任意值的Spark DataFrame,可以通过多种方式实现。使用文字值(SPARK 1.3)在尝试提供直接值时,用于此问题时,旨在为此目的的column方法可能会导致错误。 df.withco...
    编程 发布于2025-05-08
  • 如何在GO编译器中自定义编译优化?
    如何在GO编译器中自定义编译优化?
    在GO编译器中自定义编译优化 GO中的默认编译过程遵循特定的优化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    编程 发布于2025-05-08
  • 编译器报错“usr/bin/ld: cannot find -l”解决方法
    编译器报错“usr/bin/ld: cannot find -l”解决方法
    错误:“ usr/bin/ld:找不到-l “ 此错误表明链接器在链接您的可执行文件时无法找到指定的库。为了解决此问题,我们将深入研究如何指定库路径并将链接引导到正确位置的详细信息。添加库搜索路径的一个可能的原因是,此错误是您的makefile中缺少库搜索路径。要解决它,您可以在链接器命令中添加...
    编程 发布于2025-05-08
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-05-08
  • 哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    编程 发布于2025-05-08
  • 您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    您可以使用CSS在Chrome和Firefox中染色控制台输出吗?
    在javascript console 中显示颜色是可以使用chrome的控制台显示彩色文本,例如红色的redors,for for for for错误消息?回答是的,可以使用CSS将颜色添加到Chrome和Firefox中的控制台显示的消息(版本31或更高版本)中。要实现这一目标,请使用以下模...
    编程 发布于2025-05-08
  • Java为何无法创建泛型数组?
    Java为何无法创建泛型数组?
    通用阵列创建错误 arrayList [2]; JAVA报告了“通用数组创建”错误。为什么不允许这样做?答案:Create an Auxiliary Class:public static ArrayList<myObject>[] a = new ArrayList<myO...
    编程 发布于2025-05-08
  • 在JavaScript中如何获取实际渲染的字体,当CSS字体属性未定义时?
    在JavaScript中如何获取实际渲染的字体,当CSS字体属性未定义时?
    Accessing Actual Rendered Font when Undefined in CSSWhen accessing the font properties of an element, the JavaScript object.style.fontFamily and objec...
    编程 发布于2025-05-08
  • 图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    图片在Chrome中为何仍有边框?`border: none;`无效解决方案
    在chrome 中删除一个频繁的问题时,在与Chrome and IE9中的图像一起工作时,遇到了一个频繁的问题。和“边境:无;”在CSS中。要解决此问题,请考虑以下方法: Chrome具有忽略“ border:none; none;”的已知错误,风格。要解决此问题,请使用以下CSS ID块创建带...
    编程 发布于2025-05-08
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php $xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) { echo $attributeName,...
    编程 发布于2025-05-08
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-05-08
  • 在Pandas中如何将年份和季度列合并为一个周期列?
    在Pandas中如何将年份和季度列合并为一个周期列?
    pandas data frame thing commans date lay neal and pree pree'和pree pree pree”,季度 2000 q2 这个目标是通过组合“年度”和“季度”列来创建一个新列,以获取以下结果: 在Python中,可以直接使用“...
    编程 发布于2025-05-08
  • Go web应用何时关闭数据库连接?
    Go web应用何时关闭数据库连接?
    在GO Web Applications中管理数据库连接很少,考虑以下简化的web应用程序代码:出现的问题:何时应在DB连接上调用Close()方法?,该特定方案将自动关闭程序时,该程序将在EXITS EXITS EXITS出现时自动关闭。但是,其他考虑因素可能保证手动处理。选项1:隐式关闭终止数...
    编程 发布于2025-05-08
  • 在Go语言中如何简洁定义10的幂常量
    在Go语言中如何简洁定义10的幂常量
    在GO 利用浮点线文字一种简洁的方式是使用浮点文字,该方法是使用floingpoint protals。写作1E3比写作1000更有效。这是一个示例(67个没有空间的字符):的文字用于未构图的整数常数,我们可以将1000用于KB,并用KB将随后的常量乘以KB,如下所示(77个没有空格的字符):,作...
    编程 发布于2025-05-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3