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); //返回字符。
}