Javascript 简明教程

JavaScript - ES5

JavaScript 的 ES6 版本于 2015 年发布,标志着 JavaScript 的第二次重大修订。ES6 也被称为 ECMAScript 2015。ES6 中引入的一些重要功能是箭头函数、let 和 const 关键字、类、res 参数等。本章将讨论 ES6 版本中所有新添加的功能。

The ES6 version of JavaScript was released in 2015, marking the second major revision of JavaScript. The ES6 is also known as ECMAScript 2015. Some of the important features introduced in ES6 are arrow functions, let and const keywords, Classes, res parameters, etc. This chapter will discuss all the newly added features in ES6 version.

New Added Features in ES6

以下是添加到 JavaScript 的 ES6 版本中的新方法、功能等。

Here are the new methods, features, etc., added to the ES6 version of JavaScript.

  1. Arrow Functions

  2. Array find()

  3. Array findIndex()

  4. Array from()

  5. Array keys()

  6. Classes

  7. const keyword

  8. Default Parameters

  9. For/of

  10. Function Rest Parameter

  11. JavaScript Modules

  12. let keyword

  13. Map Objects

  14. New Global Methods

  15. New Math Methods

  16. New Number Methods

  17. New Number Properties

  18. Promises

  19. Set Objects

  20. String.endsWith()

  21. String.includes()

  22. String.startsWith()

  23. Symbol

  24. The spread Operator

在此,我们使用示例详细解释了每个功能。

Here, we have explained each feature in detail with examples.

JavaScript Arrow Functions

箭头函数是一种编写更短函数代码的方式。箭头函数的概念允许你在不使用函数关键字、大括号和 return 关键字的情况下定义函数。

The arrow function is a way to write the shorter function code. The concept of the arrow functions allows you to define the function without using the function keyword, curly braces, and return keyword.

Example

在以下代码中,func() 是一个常规函数,而变量 subtracts 存储箭头函数。

In the below code, func() is a regular function, and the variable subtracts stores the arrow function.

<html>
<body>
   <div id = "output">The subtraction of 20 and 10 is: </div>
   <script>
      /* Normal function
      function func(a, b) {
         return a - b;
      }
      */
      // Arrow function
      const subtract = (a, b) => a - b;
      document.getElementById("output").innerHTML += subtract(20, 10);
   </script>
</body>
</html>
The subtraction of 20 and 10 is: 10

JavaScript Array find() Method

JavaScript array.find() 方法返回遵循特定条件的第一个元素。

The JavaScript array.find() method returns the first element that follows the particular condition.

Example

在以下代码中,我们使用 array.find() 方法查找长度小于 4 的第一个数组元素。

In the below code, we find the first array element whose length is less than 4 using the array.find() method.

<html>
<body>
   <div id = "output">The first array element whose length is less than 4 is: </div>
   <script>
      const strs = ["Hello", "World", "How", "are", "You"];

      function func_len(value, index, array) {
         return value.length < 4;
      }

      document.getElementById("output").innerHTML += strs.find(func_len);
   </script>
</body>
</html>
The first array element whose length is less than 4 is: How

JavaScript Array findIndex()

JavaScript array.findIndex() 方法类似于 array.find() 方法,但它返回第一个匹配特定条件的元素的索引。它返回 0 索引。

The JavaScript array.findIndex() method is similar to the array.find() method, but it returns the index of the first element that matches the particular condition. It returns the 0-based index.

Example

在以下代码中,我们使用 array.findIndex() 方法查找长度小于 4 的第一个元素的索引。

In the below code, we find the index of the first element whose length is less than 4 using the array.findIndex() method.

<html>
<body>
   <div id = "output">The first array element whose length is less than 4 is: </div>
   <script>

      const strs = ["Hello", "World", "How", "are", "You"];

      function func_len(value, index, array) {
         return value.length < 4;
      }

      document.getElementById("output").innerHTML += strs.findIndex(func_len);
   </script>
</body>
</html>
The first array element whose length is less than 4 is: 2

JavaScriipt Array from()

JavaScript Array.from() 方法从作为参数传递的可迭代对象创建一个数组。

The JavaScript Array.from() method creates an array from the iterable passed as an argument.

Example

在以下代码中,我们使用 Array.from() 方法从字符串创建一个数组。但是,你也可以将可迭代对象作为 Array.from() 方法的参数进行传递。

In the below code, we create an array from the string using the Array.from() method. However, you can also pass iterable as an argument of the Array.from() method.

<html>
<body>
   <div id = "output">The array from the Hello string is: </div>
   <script>
      document.getElementById("output").innerHTML += Array.from("Hello");
   </script>
</body>
</html>
The array from the Hello string is: H,e,l,l,o

JavaScript Array keys()

JavaScript array.keys() 方法返回一个用于迭代键的迭代器。数组元素的键是数组元素的索引。

The JavaScript array.keys() method returns an iterator to iterate the keys. The keys of the array element are indexes of the array elements.

Example

在以下代码中,我们使用 keys() 方法获取 nums[] 数组的键的迭代器。然后,我们使用 for/of 循环来遍历数组键。

In the below code, we use the keys() method to get the iterators of keys of the nums[] array. After that, we use the for/of loop to traverse the keys of the array.

<html>
<body>
   <div id = "demo">The keys of the nums array is: <br></div>
   <script>
      const output = document.getElementById("demo");
      const nums = [45, 67, 89, 342, 123, 12];
      const iteratorNums = nums.keys();
      for (let key of iteratorNums) {
         output.innerHTML += key + "<br>";
      }
   </script>
</body>
</html>
The keys of the nums array is:
0
1
2
3
4
5

JavaScript Classes

类在面向对象编程语言中至关重要。它是对象的蓝图。

Classes are essential in the object-oriented programming language. It is a blueprint for the object.

你可以使用 class 关键字来定义类。你可以在类主体中添加构造函数、属性和方法。若要访问类属性和方法,可使用类实例。

You can use the class keyword to define the class. You can add constructors, properties, and methods to the class body. To access class properties and methods, you can use the class instance.

Example

在下方的代码中,我们定义了动物类。

In the below code, we have defined the animal class.

构造器初始化 name 和 isVegetarian 属性的值。getInfo() 方法返回动物信息。

The constructor initializes the value of the name and isVegetarian property. The getInfo() method returns the animal information.

我们创建了动物类的对象,并使用它调用类的 getInfo() 方法。

We created the object of the animal class and used it to invoke the getInfo() method of the class.

<html>
<body>
   <div id = "output">The animal information is: </div>
   <script>
      class animal {
         constructor(name, isVegetarian) {
            this.name = name;
            this.isVegetarian = isVegetarian;
         }
         getInfo() {
            return "Name : " + this.name + ", " + "isVegetarian? : " + this.isVegetarian;
         }
      }

      const lion = new animal("Lion", false);

      document.getElementById("output").innerHTML += lion.getInfo();
   </script>
</body>
</html>
The animal information is: Name : Lion, isVegetarian? : false

JavaScript const keyword

JavaScript const 关键字用于声明常量变量。您需要在声明常量变量时对其进行初始化。

The JavaScript const keyword is used to declare the constant variables. You need to initialize the constant variables while declaring them.

Example

在下方的代码中,"fruit" 是一个常量变量。您无法重新初始化它的值。

In the below code, the 'fruit' is a constant variable. You can’t reinitialize its value.

<html>
<body>
   <div id = "output">The value of the fruit variable is: </div>
   <script>
      const fruit = "Apple";
      // fruit = "Banana"; This is Invalid
      document.getElementById("output").innerHTML += fruit;
   </script>
</body>
</html>
The value of the fruit variable is: Apple

JavaScript let keyword

JavaScript let 关键字用于定义受阻的范围变量。

The JavaScript let keyword is used to define the blocked scope variables.

Example

在下方的代码中,我们在"if" 块内部使用 let 关键字定义了变量"a"。由于其范围规则,无法在"if" 块外部访问它。

In the below code, we have defined the variable 'a' using the let keyword inside the 'if' block. It can’t be accessible outside the 'if' block due to its scoping behavior.

<html>
<body>
   <div id = "output"> </div>
   <script>
      if (true) {
         let a = 20;
         document.getElementById("output").innerHTML += "The value of a is: " + a;
      }
      // You can't access it here.
   </script>
</body>
</html>
The value of a is: 20

JavaScript Default Parameters

默认参数意味着函数参数可以具有默认值。当您没有传递足够的参数到函数时,它会使用默认参数值。

The default parameters mean function parameters can have default values. When you don’t pass enough arguments to the function, it uses the default parameter values.

Example

在下方的代码中,division() 函数接受两个参数。a 的默认值为 10,b 的默认值为 2。

In the below code, the division () function takes two parameters. The default value of a is 10, and b is 2.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      function division(a = 10, b = 2) {
         return a / b;
      }
      output.innerHTML += "division(40, 5) => " + division(40, 5) + "<br>";
      output.innerHTML += "division(40) => " + division(40) + "<br>";
      output.innerHTML += "division() => " + division();
   </script>
</body>
</html>
division(40, 5) => 8
division(40) => 20
division() => 5

JavaScript for…of Loop

JavaScript for…​of 循环遍历诸如数组、字符串、集合、映射等可迭代项。

The JavaScript for…of loop traverses the iterable like an array, string, set, map, etc.

Example

在下方的代码中,我们遍历数字数组,并将数组的每个元素打印到输出中。

In the below code, we traverse the array of numbers and print each element of the array in the output.

<html>
<body>
   <div id = "output">The array elements are:  </div>
   <script>
      const array = [10, 67, 82, 75, 80];
      for (let number of array) {
         document.getElementById("output").innerHTML += number + ", ";
      }
   </script>
</body>
</html>
The array elements are: 10, 67, 82, 75, 80,

JavaScript Function Rest Parameter

当您不确定函数的参数数量时,可以使用 rest 参数。rest 参数允许您将多个参数收集到单个数组中。

When you are unsure about a number of the function argument, you can use the rest parameters. The rest parameter allows you to collect multiple arguments in a single array.

Example

我们使用 rest 参数将下面的代码传递给 sum() 函数。rest 参数的名称可以是有效的标识符,并且它与展开(…​)运算符一起使用。

We have passed the below code using the rest parameter with the sum() function. The name of the rest parameter can be a valid identifier, and it is used with the spread (…) operator.

sum() 函数添加多个数值并返回它们。

The sum() function adds the multiple numeric values and returns them.

<html>
<body>
   <div id = "output">sum(10, 67, 82, 75, 80) =  </div>
   <script>
      function sum(...restParam) {
         let res = 0;
         for (let ele of restParam) {
            res += ele;
         }
         return res;
      }
      document.getElementById("output").innerHTML += sum(10, 67, 82, 75, 80);
   </script>
</body>
</html>
sum(10, 67, 82, 75, 80) = 314

JavaScript Modules

在 JavaScript 中,您可以创建不同的模块来编写可重用代码。然后,您可以将模块导入到不同的 JavaScript 文件中。

In JavaScript, you can create different modules to write reusable code. After that, you can import the modules into the different JavaScript files.

Default Export/Import modules

const moduleMath = "This is the default value.";
export default moduleMath; // Exporting the module

在其他 JavaScript 文件中,

In other JavaScript files,

// Importing the default module
import moduleMath from './filename.js';
console.log(moduleMath);

Named Export/Import modules

您还可以从模块中导出特定函数或属性,并将它们导入到其他 JavaScript 文件中。

You can also export particular functions or properties from the modules and import them into other JavaScript files.

// Exporting variables
export const size = 90;

// Exporting function
export function add(a, b) {
  return a + b;
}

在其他 JavaScript 文件中,

In other JavaScript files,

// Importing specific properties and functions
import { size, add} from './filename.js';

console.log(myVariable); // 90
console.log(add(15, 25)); // 40

JavaScript Map Objects

映射用于存储键值对。您可以使用 Map() 构造器定义映射。

The map is used to store the key-value pairs. You can use the Map() constructor to define a map.

Example

在下面的示例中,我们使用映射来存储水果的名称和价格。set() 方法用于将键值对插入 fruit 映射中,get() 方法用于从映射中获取特定键的值。

In the example below, we use the map to store the fruit’s name and price. The set() method is used to insert the key-value pair into the fruit map, and the get() method is used to get the value of a particular key from the map.

<html>
<body>
   <div id = "output1">The price of the Apple is: </div>
   <div id = "output2">The price of the Banana is: </div>
   <script>
      const fruit = new Map();
      fruit.set("Apple", 50);
      fruit.set("Banana", 60);
      document.getElementById("output1").innerHTML += fruit.get("Apple") + "<br>";
      document.getElementById("output2").innerHTML += fruit.get("Banana");
   </script>
</body>
</html>
The price of the Apple is: 50
The price of the Banana is: 60

New Global Methods

在 ES6 中,添加了两个全局方法。

In the ES6, below two global methods are added.

  1. isFinite()

  2. isNaN()

isFinite()

isFinite() 方法检查作为参数传递的值是否是有限的。

The isFinite() method checks whether the value passed as an argument is finite.

Example

在下面的代码中,num1 变量包含无限值,num2 包含有效数字值。

In the below code, the num1 variable contains the infinity value, and num2 contains the valid numeric value.

我们使用 isFinite() 方法检查 num1 和 num2 变量的值是否有限。

We used the isFinite() method to check whether the num1 and num2 variable’s value is finite.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const num1 = 6453 / 0;
      const num2 = 90;
      document.getElementById("output").innerHTML =
	  "isFinite(6453 / 0): " + isFinite(num1) + "<br>" +
      "isFinite(90): " + isFinite(num2);
   </script>
</body>
</html>
isFinite(6453 / 0): false
isFinite(90): true

isNaN()

isNaN() 方法检查参数是否是有效数字。它对数字值返回 false。

The isNaN() method checks whether the argument is a valid number. It returns false for the number value.

Example

在下面的代码中,isNaN() 方法对 num1 变量返回 true,因为它包含字符串,而字符串不是数字。对 num2 变量,isNaN() 方法返回 false,因为它包含数字值。

In the below code, the isNaN() method returns true for the num1 variable, as it contains the string, and the string is not a number. For the num2 variable, the isNaN() method returns false, as it contains the numeric value.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const num1 = "Hello";
      const num2 = 867;
      document.getElementById("output").innerHTML =
	  "isNaN(num1):  " + isNaN(num1) + "<br>" +
      "isNaN(num2):  " + isNaN(num2);
    </script>
</body>
</html>
isNaN(num1): true
isNaN(num2): false

New JavaScript Math Methods

在 ES6 中,为 Math 对象添加了 5 个新方法。

In ES6, 5 new methods were added to the Math object.

  1. Math.cbrt() − It is used to find the cube root of the given number.

  2. Math.log2() – It is used to find the logarithm of a number and uses the base 2.

  3. Math.log10() – It finds the base 10 logarithm of numeric value.

  4. Math.trunc() – It removes the decimal part from the floating point number and converts it into the whole number.

  5. Math.sign() – It returns 1, 0, and -1 based on the sign of the number passed as an argument.

Example: Math.cbrt()

下面的代码找出了 64 的立方根。

The below code finds the cube root of the 64.

<html>
<body>
   <div id = "output">The cube root of the 64 is: </div>
   <script>
      document.getElementById("output").innerHTML += Math.cbrt(64);
   </script>
</body>
</html>

Example: Math.log2()

下面的代码找出了 30 的底 2 对数。

The below code finds the logarithm of 30 base 2.

<html>
<body>
   <div id = "output">The value of logarithm of 30 base 2 is: </div>
   <script>
      document.getElementById("output").innerHTML += Math.log2(30);
   </script>
</body>
</html>

Example: Math.log10()

下面的代码找出了 10 的底 10 对数。

The below code finds the logarithm of 10 base 10.

<html>
<body>
   <div id = "output">The value of the logarithm of 10 base 10 is: </div>
   <script>
      document.getElementById("output").innerHTML += Math.log10(10);
   </script>
</body>
</html>

Example: Math.trunc()

下面的代码使用 Math.trunc() 方法截断了浮点数。

The below code truncates the floating point numbers using the Math.trunc() method.

<html>
<body>
   <div id = "output">After converting 23.2 to integer is: </div>
   <script>
      document.getElementById("output").innerHTML += Math.trunc(23.2);
   </script>
</body>
</html>

Example: Math.sign()

<html>
<body>
   <div id="output1">Math.sign(23): </div>
   <div id="output2">Math.sign(-23): </div>
   <script>
      document.getElementById("output1").innerHTML += Math.sign(23);
      document.getElementById("output2").innerHTML += Math.sign(-23);
   </script>
</body>
</html>

New Number Methods

在 ES6 中,添加了两个新的数字方法。

In ES6, two new number methods were added.

  1. Number.isInteger() − It checks whether the number passed as an argument is a whole number or an integer.

  2. Number.isSafeInteger() − It checks whether the number can be represented as a 64-bit double number.

Example

下面的代码检查 10 和 10.5 是否是整数。此外,它使用 number 类的 isSafeInteger() 方法检查该数字是否是安全整数。

The below code checks whether 10 and 10.5 is an integer value. Also, it uses the isSafeInteger() method of the number class to check whether the number is safe integer.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      output.innerHTML += "Is 10 integer? " + Number.isInteger(10) + "<br>";
      output.innerHTML += "Is 10.5 integer? " + Number.isInteger(10.5) + "<br>";

      output.innerHTML += "Is 10000 safe integer? " + Number.isSafeInteger(10000) + "<br>";
      output.innerHTML += "Is 10000000000000000000000 safe integer? " + Number.isSafeInteger(10000000000000000000000);
   </script>
</body>
</html>
Is 10 integer? true
Is 10.5 integer? false
Is 10000 safe integer? - true
Is 10000000000000000000000 safe integer? - false

New Number Properties

在 ES6 中,添加了三个新数字属性。

In ES6, three new number properties were added.

  1. EPSILON − It returns the value of the Epsilon.

  2. MIN_SAFE_INTEGER − It returns the minimum integer value that a 64-bit number can represent.

  3. MAX_SAFE_INTEGER − returns the maximum number, which can be represented by 64-bit.

Example

下面的代码显示了 Epsilon 常量、安全整数的最小值、JavaScript 中安全整数的最大值。

The below code shows the value of the Epsilon constant, minimum value of the safe integer, maximum value of the safe integer in JavaScript.

<html>
<body>
   <div id = "output1">The value of Epsilon is: </div>
   <div id = "output2">The minimum safe integer is:  </div>
   <div id = "output3">The maximum safe integer is: </div>
   <script>
      document.getElementById("output1").innerHTML +=  Number.EPSILON;
      document.getElementById("output2").innerHTML +=  Number.MIN_SAFE_INTEGER;
      document.getElementById("output3").innerHTML +=  Number.MAX_SAFE_INTEGER
   </script>
</body>
</html>
The value of Epsilon is: 2.220446049250313e-16
The minimum safe integer is: -9007199254740991
The maximum safe integer is: 9007199254740991

JavaScript Promises

在 JavaScript 中,promise 用于异步处理代码。

In JavaScript, promises are used to handle the code asynchronously.

它生成并消耗代码。

It produces and consumes the code.

Example

在下面的代码中,我们使用 Promise() 构造函数创建一个 promise。我们根据使用 Math 块的 random() 方法生成随机值来解决并拒绝该 promise。

In the below code, we used the Promise() constructor to create a promise. We resolve and reject the promise based on the random value generated using the random() method of the Math block.

之后,我们使用 then() 和 catch() 块处理 promise。

After that, we handle the promise using the then() and catch() block.

<html>
<body>
   <div id = "output"> </div>
   <script>
      // Creating a Promise
      const newPromise = new Promise((res, rej) => {
         setTimeout(() => {
            const rand_value = Math.random();
            if (rand_value < 0.5) {
               res("Value is less than 0.5"); // Resolving the promise
            } else {
               rej("Value is greater than 0.5"); // Rejecting the promise
            }
         }, 1000); // Adding 1 second delay
      });

      // Consuming the Promise
      newPromise
         .then((res) => {
             document.getElementById("output").innerHTML += res;
          })
         .catch((rej) => {
              document.getElementById("output").innerHTML += rej;
         });
   </script>
</body>
</html>
Value is greater than 0.5

JavaScript Set Objects

Set() 构造函数用于创建一个集合。该集合仅存储不同类型的唯一元素。

The Set() constructor is used to create a set. The set stores only unique elements of different types.

Example

在下面的代码中,我们创建了一个新的集合,并将包含数字的数组作为 Set() 构造函数的参数传递。该集合仅包含唯一元素,您可以在输出中看到。

In the below code, we created a new set and passed the array containing the number as an argument of the Set() constructor. The set contains only unique elements, which you can see in the output.

<html>
<body>
   <div id = "output">The set elements are: </div>
   <script>
      const num_set = new Set([10, 20, 20, 42, 12]);
      for (let num of num_set) {
         document.getElementById("output").innerHTML += ", " + num;
      }
   </script>
</body>
</html>
The set elements are: , 10, 20, 42, 12

JavaScript New String Methods

在 ES6 中,添加了三个新的字符串方法。

In ES6, three new string methodswere added.

  1. endsWith() − checks whether the string ends with a particular substring.

  2. includes() − checks whether the string contains the substring at any position.

  3. startsWith() − checks whether the string starts with a particular substring.

Example

下面的示例演示如何使用字符串 endsWith()、includes() 和 startsWith() 方法以及帮助信息“您怎么样?我很好!”

The example below demonstrates how to use String endsWith(), includes(), and startsWith() methods with the help of an staing – "How are you? I’m fine!".

<html>
<body>
   <div id = "output1">Does string end with 'fine'? </div>
   <div id = "output2">Does string include 'are'? </div>
   <div id = "output3">Does string start with 'How'?  </div>
   <script>
      let str = "How are you? I'm fine!";
      document.getElementById("output1").innerHTML +=  str.endsWith("fine!");
      document.getElementById("output2").innerHTML += str.includes("are");
      document.getElementById("output3").innerHTML += str.startsWith("How");
   </script>
</body>
</html>
Does string end with 'fine'? true
Does string include 'are'? true
Does string start with 'How'? true

JavaScript Symbol

JavaScript Symbol 是一款原始数据类型。在 JavaScript 中,每个 Symbol 都是唯一的。您可以用它创建唯一的 ID。

The JavaScript Symbol is a primate data type in JavaScript. In JavaScript, each Symbol is unique. You may use it to create unique ids.

Example

在下面的代码中,我们定义了两个符号,并将相同的值作为参数传递。不过,这两个符号都是唯一的,您可以在输出中看到。

In the code below, we have defined two symbols and passed the same value as an argument. Still, both symbols are unique, which you can see in the output.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const sym1 = Symbol("a");
      const sym2 = Symbol("a");
      if (sym1 == sym2) {
         document.getElementById("output").innerHTML += "sym1 and sym2 are equal. <br>";
      } else {
         document.getElementById("output").innerHTML += "sym1 and sym2 are not equal.";
      }
   </script>
</body>
</html>
sym1 and sym2 are not equal.

JabaScript Spread Operator

JavaScript 展开运算符允许你创建可迭代对象的副本,例如数组、字符串等。

The JavaScript spread operator allows you a create a copy of the iterable, like array, string, etc.

Example

以下代码展示了使用展开运算符从字符串中创建字符数组。

The below code demonstrates using the spread operator to create an array of characters from the string.

<html>
<body>
   <div id = "output">The char array is: </div>
   <script>
      let str = "Hello World!";
      const char = [...str];
      document.getElementById("output").innerHTML += char;
   </script>
</body>
</html>
The char array is: H,e,l,l,o, ,W,o,r,l,d,!