简单的javascript split()按预期工作?

时间:2016-03-23 22:29:19

标签: javascript html

小提琴:https://jsfiddle.net/jzhang172/4ntjykr0/

var x="pokemon,rykrkr";
x.split(",");
document.getElementById('ok').innerHTML=x[0];
<div id="ok"></div>

这不应该显示整个单词“pokemon”,因为我指定它会用逗号分隔吗?

3 个答案:

答案 0 :(得分:3)

.split不会改变原始字符串,所以你必须这样做:

var x = "pokemon,rykrkr";
var splited = x.split(",");

document.getElementById('ok').innerHTML = splited[0];
<div id="ok"></div>

答案 1 :(得分:1)

var x="pokemon,rykrkr";
y=x.split(",");

document.getElementById('ok').innerHTML=y[0];

答案 2 :(得分:1)

它正在显示pokemon,rykrkr的第一个字符,但您需要分割的字词。

&#13;
&#13;
var x = "pokemon,rykrkr",
    words = x.split(",");

document.getElementById('ok').innerHTML = words[0];
&#13;
<div id="ok"></div>
&#13;
&#13;
&#13;