JavaScript String charAt() 方法详解
作者:半夏时间:2026-10-29 10:37:12浏览:376
本文介绍 JavaScript 中 String 对象的 charAt() 方法。该方法用于返回指定索引位置的字符,索引从 0 开始。若索引超出范围,则返回空字符串。文章包含语法格式、参数说明及具体代码示例,帮助开发者掌握字符串字符提取技巧。
charAt() 方法概述
该方法用于返回字符串中指定索引位置的字符。
字符串中的字符索引从左向右递增,起始索引为 0。
对于名为 stringName 的字符串,其最后一个字符的索引值为 stringName.length - 1。
语法与参数说明
语法格式如下:
string.charAt(index);
| 参数 | 描述 |
|---|---|
| index | 必需。表示字符串中某个位置的数字,即字符在字符串中的下标。 |
参数详细说明如下:
- index:必需参数,表示字符串中某个字符的位置索引,取值范围需介于 0 与字符串长度减 1 之间。
返回值说明:
返回指定索引位置对应的字符。
注意事项与提示:
字符串首个字符的下标为 0。若提供的 index 参数小于 0 或大于等于字符串长度,该方法将返回空字符串。
代码示例
代码实例:
以下代码演示如何从字符串 "Hello world!" 中获取索引为 1 的字符:
<script type="text/javascript">
var str="Hello world!"
document.write(str.charAt(1))
</script>
上述代码执行后的输出结果为:
e
<html>
<body>
</body>
</html>
[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]
更多示例:
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
document.writeln("<br />str.charAt(3) is:" + str.charAt(3));
document.writeln("<br />str.charAt(4) is:" + str.charAt(4));
document.writeln("<br />str.charAt(5) is:" + str.charAt(5));
</script>
</body>
</html>
此示例将产生如下结果:
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
