我有一个文本数组:
var text = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
我想按照设定的数字在数组中添加元素,然后将它们存储在一个新数组中。例如,如果我选择 3,那么新数组 (terms) 中的结果字符串将是:["a b c", "d e f", "g h i", ...]
etc
我查看了 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;
}
最佳答案
您可以使用各种 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);
关于javascript - 在数组中添加字符串 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7886450/