JavaScript String at() 方法



JavaScript String at() 方法用於從指定位置檢索字串中的單個字元。它接受一個整數值並返回一個包含單個 UTF-16 程式碼單元(JavaScript 字串使用的編碼系統)的新字串。

如果找不到給定的整數值(索引),則返回 'undefined'

JavaScript 中的 "at()" 和 "charAt()" 方法非常相似。但是,它們之間存在關鍵區別,如下所示:

  • at() 是 JavaScript 中較新的新增,而 charAt() 存在的時間更長。
  • at() 方法更簡潔,因為它可以讀取和使用負索引,而 charAt() 不支援負索引,並且在給定負索引時返回空字串。

語法

以下是 JavaScript String at() 方法的語法:

at(index)

引數

此方法接受一個名為“index”的引數,如下所述:

  • index − 要返回的字串字元的索引(或位置)。

返回值

此方法返回一個包含單個字元的新字串。

示例 1

檢索給定字串的第一個字元。

在給定的示例中,我們使用 JavaScript String at() 方法來檢索給定字串“Tutorials Point”的第一個字元。由於索引從0開始,到str.length-1結束,我們傳遞索引值 0 來檢索第一個字元。

<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("String: ", str);
   const index = 0;
   document.write("<br>Index: ", index);
   document.write("<br>The first character of string '", str, "' is: ", str.at(index));
</script>
</body>
</html>

輸出

上面的程式返回字串“Tutorials Point”的第一個字元,如下所示:

String: Tutorials Point
Index: 0
The first character of string 'Tutorials Point' is: T

示例 2

透過向 at() 方法傳遞索引來檢索給定字串的最後一個字元。

以下是 JavaScript String at() 方法的另一個示例。我們使用此方法來檢索給定字串“Hello World”的最後一個字元。由於此方法可以使用和讀取負索引,因此我們傳遞索引值-1來返回最後一個字元。

<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("String: ", str);
   const index = -1;
   document.write("<br>Index: ", index);
   document.write("<br>The last character of string '", str, "' is: ", str.at(index));
</script>
</body>
</html>

輸出

執行上述程式後,它返回字串“Hello World”的最後一個字元,如下所示:

String: Hello World
Index: -1
The last character of string 'Hello World' is: d

示例 3

比較at()charAt() 方法

在給定的示例中,我們比較 "at()" 和 "charAt()" 方法,並嘗試檢索給定字串"JavaScript"的倒數第二個元素。at() 方法處理負索引,因此索引值-2返回倒數第二個元素,而 charAt() 方法將索引值作為str.length-2來返回倒數第二個元素。

<html>
<head>
<title>JavaScript String at() Method</title>
</head>
<body>
<script>
   const str = "JavaScript";
   document.write("String: ", str);
   document.write("<br>The second last element using at(-2) method: ", str.at(-2));
   document.write("<br>The second last element using charAt(str.length-2) method: ", str.charAt(str.length-2));
</script>
</body>
</html>

輸出

以下輸出顯示了 at() 和 charAt() 方法之間的區別:

String: JavaScript
The second last element using at(-2) method: p
The second last element using charAt(str.length-2) method: p
廣告