js charAt的使用樣本

來源:互聯網
上載者:User

js charAt的使用樣本

 這篇文章主要介紹了js charAt的使用方法,需要的朋友可以參考下

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 之間,該方法將返回一個Null 字元串。 

 

執行個體 

 

在字串 "Hello world!" 中,我們將返回位置 1 的字元: 

 代碼如下:

<script type="text/javascript"> 

 

var str="Hello world!" 

document.write(str.charAt(1)) 

 

</script> 

 

以上代碼的輸出是: 

 

 

返回指定索引位置處的字元。 

 

strObj.charAt(index) 

 

參數 

 

strObj 

 

必選項。任意 String 對象或文字。 

 

index 

 

必選項。想得到的字元的基於零的索引。有效值是 0 與字串長度減 1 之間的值。 

 

說明 

 

charAt 方法返回一個字元值,該字元位於指定索引位置。字串中的第一個字元的索引為 0,第二個的索引為 1,等等。超出有效範圍的索引值返回Null 字元串。 

 

樣本 

 

下面的樣本說明了 charAt 方法的用法: 

 代碼如下:

function charAtTest(n){ 

var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 初始設定變數。 

var s; // 聲名變數。 

s = str.charAt(n - 1); // 從索引為n – 1的位置處 

// 擷取正確的字元。 

return(s); //返回字元。 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.