Heim  >  Artikel  >  Web-Frontend  >  js charAt的使用示例_javascript技巧

js charAt的使用示例_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:59:281387Durchsuche

eg:

复制代码 代码如下:









结果:

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 的字符:
复制代码 代码如下:



以上代码的输出是:

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); //返回字符。
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn