本帖最后由 Celine 于 2012-10-31 10:16 编辑
你可以使用split方法用限位器来分割一系列的名称,然后将其放在一个数组中。
例如:
[code=javascript]var my_friends = “trixie,moxie,sven,guido,hermes”;
var friend_array =
my_friends.split(“,”);
for (loop=0; loop < friend_array.length; loop++)
{
document.writeln(friend_array[loop] + " is myfriend.
");
}[/code]
这段代码将字符串my_friends分割成包含5个元素的数组。
JavaScript可以为你自动建立一个数组,所以你无需使用 new Array()。
将字符串分割成数组之后,我们使用了循环语句写出每一个名称。
我们可以利用split方法简化前面所讲到的域名提取:
[code]var the_url = prompt(“What’s the URL?”,“”);
var first_split = the_url.split(“//”);
var without_resource = first_split[1];
var second_split = without_resource.split(“/”);
var domain = second_split[0];[/code]
这段代码简化了很多而且也更容易理解。我们来分析一些这段代码:
var the_url = prompt("What's the URL?","");
提示用户输入一个URL,假设用户输入
"http://www.webmonkey.com/javascript/index.html" .
var first_split = the_url.split("//");
将用户输入的字符串分割成两块:
first_split[0]是"http:“,
first_split[1]是"Start an Online Business & Make Money in 2023 | WebMonkey”
var without_resource = first_split[1];
提取出数组中的第2个元素,所以现在without_resource是"Start an Online Business & Make Money in 2023 | WebMonkey"
var second_split = without_resource.split("/");
将without_resource分割成3块:www.webmonkey.com,javascript, 和index.html.现在你可以看到split的用途了吧?
var domain = second_split[0];
现在我们提取出新数组中的第1个元素就可得出域名。