indexOf 用法
2014-10-09来源:易贤网

indexOf用于发现一系列的字符在一个字符串中等位置并告诉你

子字符串的起始位置。如果一个字符串中部包含该子字符串则

indexOf返回returns "-1." 这里是一个例子:

var the_word = "monkey";

让我们从单词 "monkey"开始。

var location_of_m = the_word.indexOf("m");

location_of_m(字母m的位置)将为0,因为字母m位于该字符串

的起始位置。var location_of_o = the_word.indexOf("o");

location_of_o(字母o的位置)将为1。

var location_of_key = the_word.indexOf("key");

location_of_key(key的位置)将为3因为子字符串“key”以字母

k开始,而k在单词monkey中的位置是3。

var location_of_y = the_word.indexOf("y");

location_of_y)字母y的位置)是5。

var cheeky = the_word.indexOf("q");

cheeky值是-1,因为在单词“monkey”中没有字母q。

indexOf更实用之处:

var the_email = prompt("What's your email address?", "");

var the_at_is_at = the_email.indexOf("@");

if (the_at_is_at == -1)

{

alert("You loser, email addresses must

have @ signs in them.");

}

这段代码询问用户的电子邮件地址,如果用户输入的电子邮件

地址中不包含字符 则 提示用户"@你输入的电子邮件地址

无效,电子邮件的地址必须包含字符@。"

charAt

chatAt方法用于发现一个字符串中某个特定位置的字符。这里

是一个例子:

var the_word = "monkey";

var the_first_letter = the_word.charAt(0);

var the_second_letter = the_word.charAt(1);

var the_last_letter = the_word.charAt(the_word.length-1);

the_first_letter(第1个字符)是"m"

the_second_letter(第2个字符)是"o"

the_last_letter(最后一个字符)是 "y"

注意利用字符串的length(长度)属性你可以发现在包含多少个

字符。在本例中,the_word是"monkey",所以the_word.length

是6。不要忘记在一个字符串中第1个字符的位置是0,所以最后

一个字符的位置就是length-1。所以在最后一行中用了

the_word.length-1

更多信息请查看IT技术专栏

2025公考·省考培训课程试听预约报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息