JavaScript String charAt()

charAt() 方法在 字符串 中返回指定索引处的字符。

示例

// string declaration
const string = "Hello World!";

// finding character at index 1 let index1 = string.charAt(1);
console.log("Character at index 1 is " + index1); // Output: // Character at index 1 is e

charAt() 语法

charAt() 方法的语法是

str.charAt(index)

其中,str 是一个字符串。


charAt() 参数

charAt() 方法接受

  • index - 一个介于 0str.length - 1 之间的整数。如果 index 无法转换为整数或未提供,则使用默认值 0

注意: str.length 返回给定字符串的长度。


charAt() 返回值

  • 返回一个字符串,表示指定 index 处的字符。

示例 1:使用 charAt() 方法和整数索引值

// string declaration
const string1 = "Hello World!";

// finding character at index 8 let index8 = string1.charAt(8);
console.log("Character at index 8 is " + index8);

输出

Character at index 8 is r

在上面的程序中,string1.charAt(8) 返回给定字符串中索引为 8 的字符。

由于字符串的索引从 0 开始,"r" 的索引是 8。因此,index8 返回 "r"


示例 2:charAt() 中的非整数索引值

const string = "Hello World";

// finding character at index 6.3 let result1 = string.charAt(6.3);
console.log("Character at index 6.3 is " + result1);
// finding character at index 6.9 let result2 = string.charAt(6.9);
console.log("Character at index 6.9 is " + result2);
// finding character at index 6 let result3 = string.charAt(6);
console.log("Character at index 6 is " + result3);

输出

Character at index 6.3 is W
Character at index 6.9 is W
Character at index 6 is W

在此,非整数索引值 6.36.9 被转换为最接近的整数索引 6。因此,string.charAt(6.3)string.charAt(6.9) 都返回 "W",就像 string.charAt(6) 一样。


示例 3:在 charAt() 中不传递参数

let sentence = "Happy Birthday to you!";

// passing empty parameter in charAt() let index4 = sentence.charAt();
console.log("Character at index 0 is " + index4);

输出

Character at index 0 is  H

在这里,我们在 charAt() 方法中没有传递任何参数。默认索引值为 0,因此 sentence.charAt() 返回索引 0 处的字符,即 "H"


示例 4:charAt() 中超出范围的索引值

let sentence = "Happy Birthday to you!";

// finding character at index 100 let result = sentence.charAt(100);
console.log("Character at index 100 is: " + result);

输出

Character at index 100 is:

在上面的程序中,我们传递了 100 作为索引值。由于 "Happy Birthday to you!" 的索引值 100 处没有元素,charAt() 方法返回一个空字符串。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战