JavaScript中合并两个数组:生成指定格式结果的实现方法
Hey there! Let's work through how to merge your two arrays into that exact formatted third array you want. First, since you didn't share the exact structure of your original arrays, I'll cover a couple common scenarios that fit your desired output — feel free to adjust based on your actual data!
情况1:两个数组分别对应「角色详情」和「作品归属」
Suppose your two arrays look like this: one holds pairs of character names and their roles, the other holds the corresponding anime/manga they belong to:
// Array 1: Each element is [character name, character role] const roleDetails = [ ['Luffy', 'Pirate King'], ['Sanji', 'Cook'], ['Ryuk', 'Shinigami'], ['Lee', 'Weirdo :)'] ]; // Array 2: Each element matches the work for the character at the same index const works = ['One Piece', 'One Piece', 'Death Note', 'Death Note'];
To merge them into your desired format, use the map() method to loop through both arrays by index:
const mergedArray = roleDetails.map(([name, role], index) => { return `${name} : ${role} in ${works[index]}`; }); // Log the result console.log(mergedArray); // Output: // ['Luffy : Pirate King in One Piece', 'Sanji : Cook in One Piece', 'Ryuk : Shinigami in Death Note', 'Lee : Weirdo :) in Death Note']
情况2:两个数组对应不同作品的角色集合
If your two arrays are grouped by work (one for One Piece characters, one for Death Note characters), like this:
const onePieceChars = [ { name: 'Luffy', role: 'Pirate King' }, { name: 'Sanji', role: 'Cook' } ]; const deathNoteChars = [ { name: 'Ryuk', role: 'Shinigami' }, { name: 'Lee', role: 'Weirdo :)' } ];
You can format each group separately, then combine the results:
// Format One Piece characters const formattedOP = onePieceChars.map(char => `${char.name} : ${char.role} in One Piece`); // Format Death Note characters const formattedDN = deathNoteChars.map(char => `${char.name} : ${char.role} in Death Note`); // Merge the two formatted arrays const mergedArray = [...formattedOP, ...formattedDN]; console.log(mergedArray); // Same desired output as above!
Python Version (for reference)
If you're working in Python instead, here's how you'd handle the first scenario:
role_details = [ ['Luffy', 'Pirate King'], ['Sanji', 'Cook'], ['Ryuk', 'Shinigami'], ['Lee', 'Weirdo :)'] ] works = ['One Piece', 'One Piece', 'Death Note', 'Death Note'] merged_array = [f"{name} : {role} in {work}" for (name, role), work in zip(role_details, works)] print(merged_array)
内容的提问来源于stack exchange,提问作者Tezah Zulueta

