如何在 javascript 中合并两个字符串数组的元素?

How to merge elements of two string arrays in javascript?

假设我们有两个这样的 JavaScript 数组:

var firstNameArray = ["Jack", "Indiana", "James"];

var lastNameArray = ["Sparrow", "Jones", "Bond"];

我希望输出为:

var result = ["Jack Sparrow","Indiana Jones","James Bond"];

注意: firstNameArraylastNameArray 可以有动态值。

如何合并 JavaScript 中两个数组的元素以获得此结果?

var result = firstNameArray.map((it,index)=>it+' '+lastName Array[index]);

使用传统的for循环

var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
let merged = [];
for (let i = 0; i < firstNameArray.length; i++) {
  merged.push(`${firstNameArray[i]} ${lastNameArray[i]}`)
}
console.log(merged);

使用reduce方法

var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
const merged = firstNameArray.reduce((arr, item, index) => {
  arr.push(`${item} ${lastNameArray[index]}`);
  return arr;
}, []);
console.log(merged)

使用map

var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
let merged = firstNameArray.map((e,index) => {
  return `${e} ${lastNameArray[index]}`;
});
console.log(merged);

您可以使用 map 迭代任何数组(假设两个数组将包含相同数量的元素),并根据索引将两个数组元素串联起来构建新集合。

演示 :

const firstNameArray = ["Jack", "Indiana", "James"];

const lastNameArray = ["Sparrow", "Jones", "Bond"];

const finalArray = firstNameArray.map((item, index) => {
    return `${item} ${lastNameArray[index]}`
});

console.log(finalArray);