[英]Add strings in an array - Javascript
I have an array of text: 我有一个文本数组:
var text = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
I would like to add the elements in the array according to a set number and then store these in a new array. 我想根据一组编号在数组中添加元素,然后将它们存储在新数组中。 For example, if I pick 3, then the resulting strings in the new array (terms) would be: ["abc", "def", "ghi", ...]
etc 例如,如果我选择3,则新数组(条件)中的结果字符串将为: ["abc", "def", "ghi", ...]
等
I looked at Join and I can't get this to work - it seems to only be able to add the entire array together. 我看了看Join,但我无法使它工作-似乎只能将整个数组加在一起。 I'm guessing I need to use a nested loop, but I can't seem to get this to work. 我猜我需要使用嵌套循环,但似乎无法正常工作。 Here's my attempt: 这是我的尝试:
//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;
}
You can use various array functions like so: 您可以使用各种数组函数,如下所示:
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);
Variant of the above example: 以上示例的变体:
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);
Here you go: 干得好:
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.