JavaScript - ES5



JavaScript 的 ES6 版本於 2015 年釋出,標誌著 JavaScript 的第二次重大修訂。ES6 也被稱為 ECMAScript 2015。ES6 中引入的一些重要特性包括箭頭函式、let 和 const 關鍵字、類、rest 引數等。本章將討論 ES6 版本中所有新增的特性。

ES6 新增特性

以下是新增到 ES6 版本 JavaScript 中的新方法、特性等。

  • 箭頭函式
  • Array find()
  • Array findIndex()
  • Array from()
  • Array keys()
  • const 關鍵字
  • 預設引數
  • For/of
  • 函式 rest 引數
  • JavaScript 模組
  • let 關鍵字
  • Map 物件
  • 新的全域性方法
  • 新的 Math 方法
  • 新的 Number 方法
  • 新的 Number 屬性
  • Promise
  • Set 物件
  • String.endsWith()
  • String.includes()
  • String.startsWith()
  • Symbol
  • 展開運算子

這裡,我們詳細解釋了每個特性並附帶示例。

JavaScript 箭頭函式

箭頭函式是一種編寫更簡潔函式程式碼的方式。箭頭函式的概念允許您在不使用 function 關鍵字、大括號和 return 關鍵字的情況下定義函式。

示例

在下面的程式碼中,func() 是一個常規函式,變數 subtracts 儲存箭頭函式。

<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() 方法

JavaScript array.find() 方法返回第一個符合特定條件的元素。

示例

在下面的程式碼中,我們使用 array.find() 方法查詢長度小於 4 的第一個陣列元素。

<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 的索引。

示例

在下面的程式碼中,我們使用 array.findIndex() 方法查詢長度小於 4 的第一個元素的索引。

<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

JavaScript Array from()

JavaScript Array.from() 方法根據作為引數傳遞的迭代器建立一個數組。

示例

在下面的程式碼中,我們使用 Array.from() 方法從字串建立一個數組。但是,您也可以將迭代器作為 Array.from() 方法的引數傳遞。

<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() 方法返回一個迭代器來迭代鍵。陣列元素的鍵是陣列元素的索引。

示例

在下面的程式碼中,我們使用 keys() 方法獲取 nums[] 陣列的鍵的迭代器。之後,我們使用 for/of 迴圈遍歷陣列的鍵。

<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 類

類在面向物件程式語言中至關重要。它是物件的藍圖。

您可以使用 class 關鍵字來定義類。您可以向類體中新增建構函式、屬性和方法。要訪問類屬性和方法,您可以使用類例項。

示例

在下面的程式碼中,我們定義了 animal 類。

建構函式初始化 name 和 isVegetarian 屬性的值。getInfo() 方法返回動物資訊。

我們建立了動物類的物件,並用它來呼叫該類的getInfo()方法。

<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關鍵字

JavaScript const關鍵字用於宣告常量變數。宣告常量變數時需要對其進行初始化。

示例

在下面的程式碼中,“fruit”是一個常量變數。你不能重新初始化它的值。

<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關鍵字

JavaScript let關鍵字用於定義塊作用域變數。

示例

在下面的程式碼中,我們在“if”塊內使用let關鍵字定義了變數“a”。由於其作用域特性,它無法在“if”塊外部訪問。

<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預設引數

預設引數意味著函式引數可以具有預設值。當你沒有向函式傳遞足夠的引數時,它將使用預設引數值。

示例

在下面的程式碼中,division()函式接受兩個引數。a的預設值為10,b的預設值為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迴圈

JavaScript for…of迴圈遍歷可迭代物件,例如陣列、字串、集合、對映等。

示例

在下面的程式碼中,我們遍歷數字陣列並在輸出中列印陣列的每個元素。

<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函式剩餘引數

當你不確定函式引數的數量時,可以使用剩餘引數。剩餘引數允許你將多個引數收集到單個數組中。

示例

我們在下面的程式碼中使用剩餘引數和sum()函式。剩餘引數的名稱可以是有效的識別符號,它與擴充套件運算子(…)一起使用。

sum()函式將多個數值相加並返回結果。

<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 模組

在JavaScript中,你可以建立不同的模組來編寫可重用的程式碼。之後,你可以將這些模組匯入到不同的JavaScript檔案中。

預設匯出/匯入模組

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

在其他JavaScript檔案中,

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

命名匯出/匯入模組

你還可以從模組中匯出特定的函式或屬性,並將它們匯入到其他JavaScript檔案中。

// Exporting variables
export const size = 90;

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

在其他JavaScript檔案中,

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

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

JavaScript Map物件

Map用於儲存鍵值對。你可以使用Map()建構函式來定義一個Map。

示例

在下面的示例中,我們使用Map來儲存水果的名稱和價格。set()方法用於將鍵值對插入到fruit Map中,get()方法用於從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

新的全域性方法

在ES6中,添加了以下兩個全域性方法。

  • isFinite()
  • isNaN()

isFinite()

isFinite()方法檢查作為引數傳遞的值是否為有限值。

示例

在下面的程式碼中,num1變數包含無限值,num2包含有效數值。

我們使用isFinite()方法來檢查num1和num2變數的值是否為有限值。

<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。

示例

在下面的程式碼中,isNaN()方法對於num1變數返回true,因為它包含字串,而字串不是數字。對於num2變數,isNaN()方法返回false,因為它包含數值。

<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

新的JavaScript Math方法

在ES6中,向Math物件添加了5個新方法。

  • Math.cbrt() − 用於查詢給定數字的立方根。
  • Math.log2() – 用於查詢數字的對數,並使用以2為底。
  • Math.log10() – 查詢數值以10為底的對數。
  • Math.trunc() – 從浮點數中移除小數部分,並將其轉換為整數。
  • Math.sign() – 根據作為引數傳遞的數字的符號返回1、0和-1。

示例:Math.cbrt()

下面的程式碼查詢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>

示例:Math.log2()

下面的程式碼查詢以2為底的30的對數。

<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>

示例:Math.log10()

下面的程式碼查詢以10為底的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>

示例:Math.trunc()

下面的程式碼使用Math.trunc()方法截斷浮點數。

<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>

示例: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>

新的 Number 方法

在ES6中,添加了兩個新的數字方法。

  • Number.isInteger() − 檢查作為引數傳遞的數字是否為整數。

  • Number.isSafeInteger() − 檢查該數字是否可以表示為64位雙精度數。

示例

下面的程式碼檢查10和10.5是否為整數。此外,它還使用Number類的isSafeInteger()方法來檢查該數字是否為安全整數。

<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

新的 Number 屬性

在ES6中,添加了三個新的數字屬性。

  • EPSILON − 返回Epsilon的值。

  • MIN_SAFE_INTEGER − 返回64位數可以表示的最小整數值。

  • MAX_SAFE_INTEGER − 返回64位可以表示的最大數。

示例

下面的程式碼顯示了JavaScript中Epsilon常數的值、安全整數的最小值和安全整數的最大值。

<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 Promise

在JavaScript中,Promise用於非同步處理程式碼。

它產生和使用程式碼。

示例

在下面的程式碼中,我們使用Promise()建構函式建立一個Promise。我們根據使用Math塊的random()方法生成的隨機值來解決和拒絕Promise。

之後,我們使用then()和catch()塊來處理Promise。

<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物件

Set()建構函式用於建立一個Set。Set只儲存不同型別物件的唯一元素。

示例

在下面的程式碼中,我們建立了一個新的Set,並將包含數字的陣列作為Set()建構函式的引數傳遞。Set只包含唯一元素,你可以在輸出中看到這一點。

<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新的字串方法

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

  • endsWith() − 檢查字串是否以特定子字串結尾。
  • includes() − 檢查字串是否在任何位置包含子字串。
  • startsWith() − 檢查字串是否以特定子字串開頭。

示例

下面的示例演示瞭如何使用字串endsWith()、includes()和startsWith()方法以及字串“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中的原始資料型別。在JavaScript中,每個Symbol都是唯一的。你可以使用它來建立唯一的ID。

示例

在下面的程式碼中,我們定義了兩個Symbol,並傳遞了相同的值作為引數。儘管如此,這兩個Symbol仍然是唯一的,你可以在輸出中看到這一點。

<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.

JavaScript擴充套件運算子

JavaScript擴充套件運算子允許你建立一個可迭代物件的副本,例如陣列、字串等。

示例

下面的程式碼演示瞭如何使用擴充套件運算子從字串建立字元陣列。

<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,!
廣告