2014-12-08 44 views
1

其存储在3变量我试图ZIN.2.1分成3个变量
VAR1 = ZIN
VAR2 = zin.2
VAR3 = zin.2.1
分割字符串,并使用JavaScript

到目前为止我已经尝试

var text = "zin.2.1"; 
var splitted = text.split("."); 
console.log(splitted); 
console.log(splitted[0]); 

</script> 

输出:[ “ZIN”, “2”, “1”]
“ZIN”

有什么我可以尝试实现的。我是新来的js

+0

'VAR2 = zin.1'不'VAR2 = zin.2'? – dfsq 2014-12-08 07:18:05

+0

这可能会有所帮助:http://stackoverflow.com/questions/1954426/javascript-equivalent-of-phps-list – flec 2014-12-08 07:19:09

+0

@dfsq是的,它是zin.2 – 2014-12-08 07:24:29

回答

1

试试这个

function mySplit(text) { 

    var splitted = text.split("."), arr = []; 

    arr.push(splitted[0]); 
    arr.push(splitted[0] + '.'+ splitted[2]); 
    arr.push(text); 

return arr; 

} 

var text =“zin.2.1”;

console.log(mySplit(text));

输出:

["zin", "zin.1", "zin.2.1"] 

DEMO

+0

真棒工作 – 2014-12-08 07:45:24

+0

我很难存储数组值。 var first = arr [0]; var second = arr [1]; “ReferenceError:arr没有定义 我做错了什么? – 2014-12-08 08:09:58

+0

没关系得到它。谢谢:) – 2014-12-08 08:20:01

1

您可以通过阵列使用JavaScript map()功能循环,并建立每个值的字符串转换成一个新的数组:

var text = "zin.2.1"; 
 
var splitted = text.split("."); 
 

 
// build this string up 
 
var s = ""; 
 

 
var splitted2 = splitted.map(function(v) { 
 

 
    // don't add a . for the first entry 
 
    if(s.length > 0) { 
 
     s += '.'; 
 
    } 
 

 
    s += v; 
 

 
    // returning s will set it as the next value in the new array 
 
    return s; 
 
}); 
 

 
console.log(splitted2);