Javascript最後一個字元

在JavaScript中,可以使用字元串的length屬性來獲取字元串的長度,然後使用這個長度來獲取最後一個字元。

以下是如何獲取字元串中最後一個字元的示例:

let string = 'Hello World';
let lastCharacter = string.charAt(string.length - 1);
console.log(lastCharacter); // 輸出: 'd'

在上面的代碼中,我們首先定義了一個字元串string,然後我們使用string.length來獲取字元串的長度,並減去1來獲取最後一個字元的索引。最後,我們使用string.charAt(index)來獲取最後一個字元並將其賦值給lastCharacter變數。

請注意,string.charAt(index)方法只返回字元串中指定索引處的單個字元。如果你想要獲取字元串中最後一個單詞的最後一個字元,你可能需要先分割字元串並按單詞進行操作。