简体   繁体   English

如何在数组中的每个单词之间打印空格

[英]How to print a space between each word in an array

I remember seeing a function on w3school where you can print out all the words of an array and add a space between them, But no matter how much I google I can't find it. 我记得在w3school上看到一个功能,你可以打印出阵列中的所有单词并在它们之间添加一个空格,但不管我有多少google我都找不到它。

Example of how it could look: 它的外观示例:

function printWords() {
  var array = ["Car", "Bus", "Motorcykle"];
  print(array.addSpaces());
}

Thanx in advance Thanx提前

Use Array.prototype.join() . 使用Array.prototype.join() You can specify a character to put between the values, in your case: 在您的情况下,您可以指定要放在值之间的字符:

array.join(' ');

ASDFGerte has exactly the answer: ASDFGerte有完全答案:

function printWords() {
  var array = ["Car", "Bus", "Motorcykle"];
  print(array.join(" "));
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

You can store the contents of the array with the spaces in between, in the new variable array_content as described below, by consecutively iterating and storing each item of the array with the space in between. 您可以通过连续迭代和存储数组的每个项目以及其间的空间来存储数组的内容,其中包含空格,如下所述,在新变量array_content中。

 function printWords() { var array = ["Car ", "Bus ", "Motorcykle "]; var res = ' '; var array_content = ''; for (i = 0; i < array.length; i++) array_content = array_content + array[i] + res; console.log(array_content); } printWords(); 

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

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