【问题标题】:How to concatenate two arrays using for loops on javascript?如何在javascript上使用for循环连接两个数组?
【发布时间】:2021-12-30 08:35:43
【问题描述】:

我想通过 for 循环合并两个数组并将它们分配到一个新数组中。
我有这两个数组:

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 'Lando Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];
const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 'Aston Martin', 'Alpha Tauri'];

我想为这些“驱动程序”中的每一个分配一个涂装(不一定是他们代表的真实驱动程序),但每次我尝试调整我的代码时,我最终都会为每个驱动程序分配所有涂装,而我只想给他们一个,否则我设法只获得阵列上最后一个“驱动程序”和最后一个“制服”。

我的代码的所有版本通常都围绕着这个:

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 'Lando Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];
const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 'Aston Martin', 'Alpha Tauri'];
let resultArray = [];

const loopIndex = (arrays, arrays2) => {
    for (i = 0; i < arrays.length; i++)
        for (j = 0; j < arrays2.length; j++)
            resultArray = arrays[i].concat(arrays2[j]);
}; 

loopIndex(drivers, livery);
console.log(resultArray); //Inputs TsunodaAlpha Tauri

预期输出:

resultArray = ['VerstappenRedBull','HamiltonMercedes Benz','RaikkonenMcLaren','BottasFerrari','Lando NorrisAston Martin','LeclercAlpha Tauri','RicciardoRed Bull','VettelMercedes-Benz','StrollMcLaren','TsunodaFerrari'];

或者类似的东西,我只是想看看我是否可以使用 for 循环将一个驱动程序与一种涂装连接起来。

【问题讨论】:

  • 当你只想要 一个 元素时,为什么arrays2 会有一个循环?
  • 预期的输出是什么样的?
  • 要向数组中添加新项,您需要使用 Array.push,而不是等号。所以应该是resultArray.push( arrays[i].concat(arrays2[j]) ) - 这是前进的一步。
  • 除了@Andreas 已经问过的内容之外,由于驱动程序数组和制服数组的长度不同,分配团队的标准应该是什么?每个车手都有一个随机选择的团队吗?司机[0] 得到制服[0],司机[1] 得到制服[1]……司机[5] 得到制服[5] 然后司机[6] 得到制服[0] 等等?
  • 1.您为 resultArray 分配一个新值的每个循环。如果您想使用 push() 方法 2 向数组添加新元素。如果有意义的话,字符串的工作方式几乎与 JavaScript 中的数组一样。你concat() 每个循环有两个字符串。 3. 你不想创建一个对象数组吗? 4. 将驾驶员分配给涂装(1 辆涂装可以有 2-3 名驾驶员)而不是涂装分配给驾驶员不是更有意义吗?

标签: javascript arrays for-loop


【解决方案1】:

如果你想使用 for 循环,你可以这样做:

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 'Lando Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];

const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 'Aston Martin', 'Alpha Tauri'];

const resultArray = [];

for (let i = 0; i < drivers.length; i++) {
  const j = i % livery.length;

  resultArray.push(`${drivers[i]} | ${livery[j]}`);
}

/*
or the slightly more compact version, using forEach:

drivers.forEach((driver, index) => {
  const j = index % livery.length;
  
  resultArray.push(`${driver} | ${livery[j]}`);
})
*/

console.log(resultArray);

无论如何我建议使用Array.prototype.map():

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 'Lando Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];

const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 'Aston Martin', 'Alpha Tauri'];

const resultArray = drivers.map((driver, index) => {
  const j = index % livery.length;
  
  return `${driver} | ${livery[j]}`
});

console.log(resultArray)

[编辑] 在线 const j = index % livery.length; 的解释

由于driverslivery 数组有两种不同的长度,在某些时候你会“用完团队”,你需要指示你的代码回到livery 数组的开头。

const arr1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
const arr2 = ['a', 'b', 'c', 'd', 'e', 'f']
// expected output: ['Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Ga', 'Hb', 'Ic', 'Jd', 'Ke'];

第一个尝试性的方法可能是:

arr1.forEach((item, indexArr1) => {
  const indexArr2 = indexArr1 < arr2.length ? indexArr1 : indexArr1 - arr2.length
  // ...
})

只要arr1 的大小是arr2 的两倍,它就可以工作;但是如果arr1 有 11 个项目而 arr2 只有 5 个呢?
indexArr1 为 10(第 11th 项)时,indexArr2 将计算为 10 - 5 = 5,这不是 arr2 的有效索引(其索引从 0 到 4 )。

幸运的是,我们有 % 运算符,它返回两个数字之间的除法提示,并以这种方式工作:

indexArr1 arr2.length indexArr2 logic
0 5 0 0 / 5 = 0 (reminder 0)
1 5 1 1 / 5 = 0 (reminder 1)
2 5 2 2 / 5 = 0 (reminder 2)
3 5 3 3 / 5 = 0 (reminder 3)
4 5 4 4 / 5 = 0 (reminder 4)
5 5 0 5 / 5 = 1 (reminder 0)
6 5 1 6 / 5 = 1 (reminder 1)
7 5 2 7 / 5 = 1 (reminder 2)
8 5 3 8 / 5 = 1 (reminder 3)
9 5 4 9 / 5 = 1 (reminder 4)
10 5 0 10 / 5 = 2 (reminder 0)
11 5 1 11 / 5 = 2 (reminder 1)
12 5 2 12 / 5 = 2 (reminder 2)
13 5 3 13 / 5 = 2 (reminder 3)
14 5 4 14 / 5 = 2 (reminder 4)
... ... ... ...

【讨论】:

  • 谢谢!这正是我想要的!
  • 您能否解释一下const j = i % livery.length; 背后的原因?提前谢谢!
  • 我将在答案中添加const j = i % livery.length; 的解释,因为 cmets 的格式有限。
  • @EmmanuelBalderas 解释已添加 ;)
  • 你是最棒的,非常感谢!你不知道我有多感激。
【解决方案2】:

一种方法如下

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 'Lando 
    Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];
const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 'Aston 
    Martin', 'Alpha Tauri'];
let resultArray = [];

const loopIndex = (arrays, arrays2) => {
    console.log(arrays,arrays2);
    for (i = 0; i < arrays.length; i++)
        resultArray.push(arrays[i])
    for (j = 0; j < arrays2.length; j++)
        resultArray.push(arrays2[j])
}; 

loopIndex(drivers, livery);
console.log(resultArray); //Inputs TsunodaAlpha Tauri

//结果如下(最终数组包含 16 个项目,第一个数组中的 10 个和 来自第二个数组的 6 个)

  [1]: https://i.stack.imgur.com/sgrUk.png

【讨论】:

  • 这 100% 有效,但我正在朝着不同的方向努力,我已经用预期的输出更新了这个问题,非常感谢。
  • 检查您的预期输出将检查我是否可以解决新的问题陈述。如果您喜欢此解决方案,只需支持此特定答案即可。期待尽快解决您的新问题。欢迎您。
【解决方案3】:

根据输出要求,您需要执行以下操作

const drivers = ['Verstappen', 'Hamilton', 'Raikkonen', 'Bottas', 
'Lando Norris', 'Leclerc', 'Ricciardo', 'Vettel', 'Stroll', 'Tsunoda'];
    const livery = ['Red Bull', 'Mercedes-Benz', 'McLaren', 'Ferrari', 
'Aston Martin', 'Alpha Tauri'];
     let resultArray = [];

     const loopIndex = (arrays, arrays2) => {
        arrays.forEach((arrayItem, i) =>
        {
            const j = i % arrays2.length;
            resultArray.push(`${arrayItem}${arrays2[j]}`)
        });
    }; 

loopIndex(drivers, livery);
console.log(resultArray); //Inputs TsunodaAlpha Tauri

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 2020-02-24
    • 2019-10-30
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多