简体   繁体   English

如何使用javascript在循环中每行添加一个新字符?

[英]How do you add a new character per line in a loop with javascript?

Not sure if the title makes sense, but I'm trying to figure out how to make a loop in javascript that would add a character each time it loops.不确定标题是否有意义,但我试图弄清楚如何在 javascript 中创建一个循环,每次循环时都会添加一个字符。 Say for example I want to add a "0" for each line, so the output would look like this...比如说我想为每一行添加一个“0”,所以输出看起来像这样......

0 0

00 00

000 000

0000 0000

This is what I have so far这是我到目前为止

var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 4; count++){
  document.write("0");
  document.write("<br />");
}
document.write("Loop stopped!");

You really shouldn't use document.write , but here's a solution with the same structure:你真的不应该使用document.write ,但这里有一个具有相同结构的解决方案:

var count;
var str = '0';
document.write("Starting Loop" + "<br />");
for(count = 0; count < 4; count++, str += '0'){
  document.write(str);
  document.write("<br />");
}
document.write("Loop stopped!");

JSFiddle JSFiddle

If the character you want added does not change then I suggest something like:如果您想要添加的角色没有改变,那么我建议如下:

   var count;
   var s = "0";
   var endChar = "0"
   document.write("Starting Loop" + "<br />");
   for(count = 0; count < 4; count++){
       document.write(s);
       document.write("<br />");
       s += endChar;
   }
   document.write("Loop stopped!");

So build a string and keep adding to it所以建立一个字符串并不断添加它

var s = "0";
console.log(s);
for(var count = 1; count < 4; count++){
    s = s + "0";
    console.log(s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 javascript 字符串中插入换行符,即“↵”作为字符(ASCII 值 10)而不将其分成新行? - How to do you insert new line character ie “↵” as a character (ASCII VALUE 10) in a javascript string without breaking it into a new line? 您如何限制 Javascript for 循环与 API 调用,每秒 4 个调用块? - How do you throttle a Javascript for loop with an API call within, in chunks of 4 calls per second? 如何换行或将HTML添加到此Javascript函数? - How do I make a new line or add HTML to this Javascript function? 如何在ajax responsetext中添加换行符 - How to add new line character in ajax responsetext 如何在 Javascript 中替换换行符? - How to replace a new line character in Javascript? 在NodeJS中,如何在不手动添加换行符的情况下将行打印到文件中? - In NodeJS, how do you print lines to a file without manually adding the new line character? 如何从Servlet中将新行字符传递给JavaScript? - How do I pass a New line character to JavaScript from my Servlet? 如何使用 for 循环添加新行? - How to add a new line using for loop? 每行javascript textarea字符限制 - javascript textarea character limit per line 如何在Javascript循环中每个字符串获取一行 - How to get a single line per string in Javascript loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM