简体   繁体   中英

javascript slice within loop for array

I want to take an array output like the following:

 [a,
  b,
  c,
  d,
  e,
  f]

and slice it into sections, then output each new array on a newline like this:

 [a,b
  c,d
  e,f]

Here's what i have so far:

var data = "";
for (i = 0; i < 4; i+=2) {
data += output.slice(i,2);

}
return data;

I've been working at this for some time now trying different things to make this work but no luck. I'm new to JS, so i need some help.

Since you have six elements in your array, you need to iterate to 6 not 4. The best way to do that is to use the length of your array, so if the length changes you don't need to change the loop. When taking a slice you also want slice(i, i+2)

If you just want to make a string, you can add a \\n character in each iteration:

 let output = ['a', 'b', 'c', 'd', 'e', 'f'] var data = ""; for (i = 0; i < output.length; i+=2) { data += output.slice(i,i+2).join(" ") + "\\n"; } console.log(data); 

 let data = ['a', 'b', 'c', 'd', 'e', 'f'] var output = ""; for (i = 0; i < data.length; i+=2) { output += data.slice(i, i+2).join(",") + "\\n"; } console.log(`[${output.substring(0, output.lastIndexOf("\\n"))}]`); 

Assuming they are only chars (1 char) and there are not empty chars, you can join , match the chars as pairs using the regex /(.+?){2}/g , map to char,char and finally join with \\n .

 let output = ['a', 'b', 'c', 'd', 'e', 'f'], data = output. join(''). match(/(.+?){2}/g). map(s => s.split('').join(',')).join('\\n'); console.log(data); 

While zos0K's answer should suffice for slicing, one point I would like to mention is that if you just want to output the string and do nothing else with the resulting sliced arrays, I would recommend that you directly add them to a string and then print it out as aposed to creating a new array for every couple strings. While it does the job, Array.prototype.slice returns a new array each time, and creating new arrays can get expensive fairly quickly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM