2014-12-08 94 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);