如何使用字符串中的数组元素打印多个句子?

时间:2017-04-14 15:35:11

标签: javascript

我正在尝试创建一个简单的JavaScript函数,它将一个字符串作为输入。例如,如果我的"放置"数组有元素," house"," farm"," barn"," hotel"我输入了这个字符串:

Hello, welcome to my $place. I hope you like it here at my $place.

输出将是:

Hello, welcome to my house. I hope you like it here at my house.
Hello, welcome to my farm. I hope you like it here at my farm.
Hello, welcome to my barn. I hope you like it here at my barn.
Hello, welcome to my hotel. I hope you like it here at my hotel.

3 个答案:

答案 0 :(得分:0)

您可以将元素存储在数组中,然后迭代它,例如使用Array#forEach并使用数组中的指定元素记录每个字符串。

var place = ["house", "farm", "barn", "hotel"];
    place.forEach(v => console.log("Hello, welcome to my " + v + ". I hope you like it here at my " + v + "."));

如果要准确显示用户输入的内容,请使用以下方法。

var place = prompt();

console.log("Hello, welcome to my " + place + ". I hope you like it here at my " + place + ".");

答案 1 :(得分:0)

使用一些不错的ES2015功能(块范围变量,模板文字和箭头功能)。

let places = ["house", "farm", "barn", "hotel"];
places.forEach(a=>console.log(`Hello, welcome to my ${a}!`));

或者,一些不错的发电机功能呢?

function* welcome2places(placesArray) {
  let places = placesArray;
  yield* places;
}
let welcome = welcome2places(["house", "farm", "barn", "hotel"]);
let welcomeMessage = welcome.next();
while (!welcomeMessage.done) {
   console.log(`Welcome to my ${welcomeMessage.value}!`);
   welcomeMessage = welcome.next();
}

答案 2 :(得分:0)

可以用句子映射每个数组元素,用元素替换所有出现的“$ place”...

console.log(["house","farm"].map(el=>"Hello, welcome to my $place. I hope you like it here at my $place.".split("$place").join(el)).join("\n");