這個方法傳回從指定索引的字元。
字元串中的字元進行索引從左向右。第一個字元的索引是0,并且在一個叫 stringName字元串的最後一個字元的索引是
stringName.length- 1。
文法
string.charAt(index);
參數
描述
index
必需。表示字元串中某個位置的數字,即字元在字元串中的下标。
下面是參數的詳細資訊:
index: 介于0和1比串的長度以下的整數。
傳回值:
傳回從指定索引的字元。
提示和注釋
注釋:字元串中第一個字元的下标是 0。如果參數 index 不在 0 與 string.length 之間,該方法将傳回一個空字元串。
執行個體
在字元串 "Hello world!" 中,我們将傳回位置 1 的字元:
var str="Hello world!"
document.write(str.charAt(1))
以上代碼的輸出是:
e
例子:
JavaScript String charAt() Method
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("
str.charAt(1) is:" + str.charAt(1));
document.writeln("
str.charAt(2) is:" + str.charAt(2));
document.writeln("
str.charAt(3) is:" + str.charAt(3));
document.writeln("
str.charAt(4) is:" + str.charAt(4));
document.writeln("
str.charAt(5) is:" + str.charAt(5));
這将産生以下結果:
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