将两个数组组合成一个新的字符串数组

时间:2018-04-19 16:31:04

标签: javascript html arrays

对于令人困惑的标题感到抱歉,但我不确定如何单独在标题中解释。我想从两个其他数组创建一个新数组,其中两个数组之间有单词。换句话说,我想基本上创建它:

var author_title = [“authors [i]写书[i]”];

所以数组的一个值就是“托尔斯泰写下了战争与和平”。显然上面的代码不起作用,否则我不会在这里。那么如何将这两个数组合并呢?这是我到目前为止的代码减去一些html的东西。

var books = ["War and Peace","Huckleberry Finn","The Return of the Native","A 
Christmas Carol","Exodus"];

var authors = [];

for (var i = 0; i < books.length; i++)
{

var name = prompt("What is the last name of the author who wrote " +books[i]+ 
"?");
authors.push(name);
}

document.write("***************************");

for (var i = 0; i < books.length; i++)
{

document.write("<br>");
document.write("Book: "+books[i]+ " Author: "+authors[i]);


}
document.write("<br>");
document.write("***************************");

for (var i = 0; i < books.length; i++)
{

var author_title = ["authors[i] wrote books[i]"];

}

3 个答案:

答案 0 :(得分:3)

替换

for (var i = 0; i < books.length; i++)
{

var author_title = ["authors[i] wrote books[i]"];

}

var author_title = [];
for (var i = 0; i < books.length; i++)
{

author_title.push(authors[i] + " wrote " + books[i]);

} 

答案 1 :(得分:1)

const authorTitle = books.map((book, i) => `${authors[i]} wrote ${book}`);

答案 2 :(得分:0)

您还可以使用map

更优雅地解决此问题

const books = ["War and Peace","Huckleberry Finn"];
const authors = ["Leo Tolstoy", "Mark Twain"];

const author_title = books.map((book, i) => `${authors[i]} wrote ${book}`);
console.log(author_title)