eg:
<html>
<body>
<script type="text/javascript">
var str="Hello world!"
document.write("The first character is: " + str.charAt(0) + "<br />")
document.write("The second character is: " + str.charAt(1) + "<br />")
document.write("The third character is: " + str.charAt(2))
</script>
</body>
</html>
结果:
The first character is: H
The second character is: e
The third character is: l
定义和用法
charAt() 方法可返回指定位置的字符。
请注意,JavaScript 并没有一种有别于字符串类型的字符数据类型,所以返回的字符是长度为 1 的字符串。
语法
stringObject.charAt(index)
参数 | 描述 |
---|---|
index | 必需。表示字符串中某个位置的数字,即字符在字符串中的下标。 |
提示和注释
注释:字符串中第一个字符的下标是 0。如果参数 index 不在 0 与 string.length 之间,该方法将返回一个空字符串。
实例
在字符串 "Hello world!" 中,我们将返回位置 1 的字符:
<script type="text/javascript"> var str="Hello world!" document.write(str.charAt(1)) </script>
以上代码的输出是:
e
返回指定索引位置处的字符。
strObj.charAt(index)
参数
strObj
必选项。任意 String 对象或文字。
index
必选项。想得到的字符的基于零的索引。有效值是 0 与字符串长度减 1 之间的值。
说明
charAt 方法返回一个字符值,该字符位于指定索引位置。字符串中的第一个字符的索引为 0,第二个的索引为 1,等等。超出有效范围的索引值返回空字符串。
示例
下面的示例说明了 charAt 方法的用法:
function charAtTest(n){ var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //
初始化变量。var s; //
声名变量。s = str.charAt(n - 1); //
从索引为n – 1
的位置处//
获取正确的字符。return(s); //
返回字符。 }