简体   繁体   English

如何在Javascript中的for循环之间放置空格

[英]How to put spaces in between a for loop in Javascript

I am wondering how to put a space in between each array item when printing to the console.我想知道如何在打印到控制台时在每个数组项之间放置一个空格。 I have tried messing with the countries[i] but I usually get an error in the console.我试过搞乱countries[i]但我通常会在控制台中收到错误消息。

 var countries = ["France", "Germany", "Austria"] var i var s = "" for (i = 0; i < countries.length; i++) { s += countries[i] } console.log(s)

Using .join() :使用.join()

 var countries = ["France", "Germany", "Austria"]; var spaced = countries.join(' '); console.log(spaced);

you can use join :你可以使用join

Ex: countries.join(' ');例如: countries.join(' ');

or concat a space on the end:或在末尾连接一个空格:

s += countries[i] + ' '

So you want following as the end result?所以你想跟随作为最终结果?

France Germany Austria法国 德国 奥地利

There is a function in JavaScript to concatenate all elements of an array into a new string: JavaScript 中有一个函数可以将数组的所有元素连接成一个新字符串:

join()

More info on this function: Array.prototype.join()关于这个函数的更多信息: Array.prototype.join()

By default the ',' is the separator but you can also specify one, such as a space.默认情况下,',' 是分隔符,但您也可以指定一个分隔符,例如空格。 So this is the way to do it:所以这是这样做的方法:

 var countries = ["France", "Germany", "Austria"]; var countryString = countries.join(' '); console.log(countryString);

Here is one approach:这是一种方法:

let a = ["France", "Germany", "Austria"];
let s = '';
for (let s2 of a) {
   if (s != '') {
      s += ' ';
   }
   s += s2;
}
console.log(s);

or you could just Join:或者你可以加入:

let s = a.join(' ');

Simply use Spread Operator during console logging.只需在控制台日志记录期间使用Spread Operator In your case use,在您的情况下使用,

console.log(...countries);

You essentially just need to concat a space character to the end of each string you are adding您基本上只需要在要添加的每个字符串的末尾连接一个空格字符

var countries = ["France", "Germany", "Austria"]
var i
var s = ""

for (i = 0; i < countries.length; i++) {
  s += countries[i] + " "
}

console.log(s)

You could do it in a better way as follows using the join() method provided by JavaScript -您可以使用 JavaScript 提供的join()方法以更好的方式执行以下操作 -

 var countries = ["France", "Germany", "Austria"] // Alternative better way - var s = countries.join(' ') console.log(s) // Your method is unnecessarily long but can be done as - /* var i; var s = "" for(i = 0; i < countries.length; i++) { s += countries[i]; if(i !== countries.length -1) s+= " "; } */

As a side tip, whenever you use JavaScript, try to see if you can use the built-in methods provided in JS.作为小提示,无论何时使用 JavaScript,请尝试查看是否可以使用 JS 中提供的内置方法。 Most of the situation could be handled using an inbuilt method and you would never need to use an explicit for loop for most of the time.大多数情况都可以使用内置方法处理,并且大多数情况下您永远不需要使用显式for循环。

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

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