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: ["a b c", "d e f", "g h i", ...]
etc
I looked at Join and I can't get this to work - it seems to only be able to add the entire array together. 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;
}
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: ["a b c", "d e f", "g h i", ...]
etc
I looked at Join and I can't get this to work - it seems to only be able to add the entire array together. 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;
}
Share
Improve this question
edited Aug 5, 2018 at 13:46
Salman Arshad
273k84 gold badges444 silver badges534 bronze badges
asked Oct 25, 2011 at 8:15
tomptomp
751 gold badge1 silver badge9 bronze badges
2 Answers
Reset to default 4You 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());
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744149192a4560567.html
评论列表(0条)