JavaScript字符串charAt()
JavaScript的字符串的charAt()方法返回在字符串中指定索引处的字符 。
charAt()
方法的语法为:
str.charAt(index)
在这里, str是一个字符串。
charAt()参数
charAt()
方法采用:
- index – 0到str.length-1之间的整数。如果不能将index转换为整数或不提供index ,则使用默认值0 。
从charAt()返回值
- 返回一个字符串,该字符串表示指定索引处的字符 (恰好是一个UTF-16代码单元)。
注意 :如果索引超出范围,则charAt()
返回一个空字符串 。
示例:使用charAt()方法
let sentence = "Happy Birthday to you!"; let index1 = sentence.charAt(2); console.log("Character at index 2:" + index1); // 'p' // index is converted to integer let index2 = sentence.charAt(6.5); // 'B' console.log("Character at index 6:" + index2); // Empty string if index out of range let index3 = sentence.charAt(100); console.log("Character at index 100:" + index3); // '' // default value is 0 let index4 = sentence.charAt(); console.log("Character at index 0:" + index4); // 'H'
输出
Character at index 2: p Character at index 6: B Character at index 100: Character at index 0: H
推荐阅读: JavaScript字符串charCodeAt()
总计 0 评论