将两个数组配对,长度不同

时间:2017-11-23 15:45:00

标签: javascript arrays loops

我想知道如何实现这种情况:我有2个字符串数组,比如说:

var cars = ["Saab", "Volvo", "BMW", "Mercedes", "Fiat"];

第二个是:

var colour = ["red", "blue", "green"];

我想制作一个循环,例如7个交互循环从两个数组中选择7对,如下所示:

   1st iteration "Saab" "red", 
   2nd iteration "Volvo" "blue", 
   3th iteration "BMW" "green", 
   4th iteration "Mercedes" "red", 
   5th iteration "Fiat" "blue", 
   6th iteration "Saab" "green", 
   7th iterathion "Volvo" "red"

因此它将第一个数组与第二个数组匹配,如果数组没有值则从头开始。

2 个答案:

答案 0 :(得分:2)

使用Array#mapcars进行迭代,并使用索引(i)上的% operator (remainder)来获得匹配的颜色:

var cars = ["Saab", "Volvo", "BMW", "Mercedes", "Fiat"];
var colour = ["red", "blue", "green"];

var result = cars.map(function(car, i) {
  return [car, colour[i % colour.length]]; // convert to whatever result you need
});

console.log(result);

答案 1 :(得分:2)

你可以计算并利用remainder operator %的优势和实际数组的长度。



.as-console-wrapper { max-height: 100% !important; top: 0; }

Error: No matching signature for function IF for argument types: BOOL, STRUCT. 
Supported signature: IF(BOOL, ANY, ANY) at [12:11]