如何使用 Javascript 执行字符串拆分并访问数组的值?
我一直在尝试进行分裂,但到目前为止我还没有成功。
到目前为止,这是我所拥有的:
我初始化一个简单的字符串:
var str = "matt.williams:STRING:ClassWork|1902122:STRING:AskAFriend";
然后我的下一步是输出数组的值:
var m = str.split("|");
var x = new Array();
x=m;
for (z in x)
{
document.write(z + "<br />");
}
但是,它会生成以下内容:
0
1
但是我想要输出的是:
matt.williams:STRING:ClassWork
1902122:STRING:AskAFriend
I have been trying to perform a split, but so far I have not had success.
Here is what I have so far:
I initialize a simple String:
var str = "matt.williams:STRING:ClassWork|1902122:STRING:AskAFriend";
My next step is then to output the values of the Array:
var m = str.split("|");
var x = new Array();
x=m;
for (z in x)
{
document.write(z + "<br />");
}
However, it produces this:
0
1
But What I want to output is this:
matt.williams:STRING:ClassWork
1902122:STRING:AskAFriend
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将此行更改
为:
Change this line:
to
你不需要设置那么多变量。您可以拆分并迭代返回的数组。
You don't need to set so many variables. You can split and iterate on the returned array.
您的 for 循环为您提供数组的索引,而不是实际值。将其更改为:
或者仅使用老式的 for 循环:
Your for loop is giving you the indexes of your array, not the actual values. Change it to:
Or just use an old fashioned for loop:
这两个答案都是正确的,我只是想补充一点
split()
返回一个数组,因此您不需要添加另一个。Both of these answers are correct, I just wanted to add that
split()
returns an Array so you don't need to add another.