2011-10-25 60 views
1

我有文字的數組:添加字符串數組 - 的Javascript

var text=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"); 

我想根據一組數字陣列中添加的元素,然後存儲這些在一個新的數組。例如,如果我選擇3,那麼新數組(術語)中的結果字符串將是:「abc」,「def」,「ghi」等。

我看着Join,並且無法獲取此內容工作 - 它似乎只能將整個陣列添加到一起。我猜我需要使用嵌套循環,但我似乎無法得到這個工作。這是我的嘗試:

//Outer loop 
for (i=0; i < text.length; i++) { 
    //Inner loop 
    for (j=i; j < i+$numberWords; j++) { 
    newWord=text[j]; 
    newPhrase=newPhrase+" "+newWord; 
    }  
terms.push(newPhrase); 
i=i+$numberWords; 
} 

在此先感謝。

回答

4

您可以使用各種array functions像這樣:

var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s"); 
var output = new Array(); 
var length = 3; 
for (var i = 0; i < input.length; i += length) { 
    output.push(input.slice(i, i + length).join(" ")); 
} 
alert(output); 

變上面的例子:

var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s"); 
var output = new Array(); 
var length = 2; 
while (input.length) { 
    output.push(input.splice(0, length).join(" ")) 
} 
alert(output); 
+0

非常感謝您的非常快的答覆 - 這很好用! – tomp

1

在這裏你去:

var text=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s"); 

var n = 3; 
var a = new Array(); 
for (var i = 0; i < Math.ceil(text.length/3); i++) 
{ 
    var s = ''; 
    for (var j = 0; (j < n) && ((i*n)+j < text.length) ; j++) 
    { 
    s += text[n*i+j] + ' '; 
    } 
    a.push(s.trim()); 
} 
+0

您可以使用'.ceil()'而不是'.floor()'來獲取第19個元素。 –

+0

啊對,當我測試它時忘了複製它,我有一個floor()+ 1。但是,拼接它是更酷的;) – PiTheNumber

+0

也感謝您的回覆 – tomp