代码之家  ›  专栏  ›  技术社区  ›  totalnoob

如何在JavaScript中交织两个数组?

  •  1
  • totalnoob  · 技术社区  · 8 年前

    我对运行这个程序感到非常困惑,因为嵌套循环对我来说仍然有点滑稽。

    使用以下两个数组:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    

    我怎么把它打印出来 一个值来自 ,然后 z中的两个值 在那之后等等?

    'y',
    'x',
    'x',
    'y',
    'x',
    'x',
    'y',
    'x',
    'x'
    

    如果值改为:

    let a = ['y','y'];
    let z = ['x','x','x','x','x'];
    

    它会打印:

    'y',
    'x',
    'x',
    'y',
    'x',
    'x',
    'x'
    

    这就是我目前所做的尝试:

    for (let i = 0; i < a.length; i++) {
        console.log(a[i]);
        for (let j = 0; j < z.length; j++) {
          console.log(z[j], z[j+1]);
        // break?
        }
    }
    11 回复  |  直到 8 年前
        1
  •  0
  •   protoproto    8 年前

    我修复你的回路:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    for (let i = 0; i < a.length; i++) {
      console.log(a[i]);
      console.log(z[i*2], z[i*2+1]);
    }
        2
  •  0
  •   Ahmet Taşgöz    8 年前

    `
    let a = ['y','y'];
    let z = ['x','x','x','x','x'];
    let j = 0;
    for (let i = 0; i < a.length; i++) {
      console.log(a[i]);
      for (j; j < z.length; j++) {
        console.log(z[j], z[j+1]);
        if(j % 2 == 1){
           break;
        }
      }
    }`

    试试这个。

        3
  •  0
  •   Eddie    8 年前

    你有一个选择就是 do / while 循环。使用 shift() 删除第一个第项,共项阵列

    let a = ['y1', 'y2', 'y3'];
    let z = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6'];
    
    //Copy the array a and z
    let aTemp = [...a]; 
    let zTemp = [...z];
    
    do {
      if (aTemp.length) console.log(aTemp.shift());
      if (zTemp.length) console.log(zTemp.shift());
      if (zTemp.length) console.log(zTemp.shift());
    } while (aTemp.length || zTemp.length); //Loop while both the temp variables have elements
        4
  •  0
  •   Jonas Wilms    8 年前
      let aIndex = 0, zIndex = 0;
    
     while(aIndex < a.length || zIndex < z.length) {
        console.log(
          a[aIndex++],
          z[zIndex++],
          z[zIndex++]
       );
     }
    
        5
  •  0
  •   WarPro    8 年前

    这是一种非破坏性的方法

    var pointer = 0;
    
        for (let i = 0; i < a.length; i++) {
          var count = 0;
          console.log(a[i]);
          for (let j = pointer; j < z.length; j++) {    
            console.log(z[j]);
            count++;
    
            if(count == 2){
                count = 0;
                if(i == a.length-1) { continue; }else { pointer = j+1; break; }
            }
    
          }
        }
    
        6
  •  0
  •   Abdulfatai    8 年前
    let c = j = 0;
    z.map(function(item){
      if(c === 0 && a[j]){ console.log(a[j++]); }
      console.log(item);
      c = c > 0 ? 0 : c + 1;
    });
    
        7
  •  0
  •   htoniv    8 年前

    请看一下下面的代码。我将您的预期输出结果推送到一个数组中。

        let a = ['y','y'];
        let z = ['x', 'x', 'x', 'x', 'x'];
        let arr = [];
        for (let i = 0; i < a.length; i++) {
            var count = 0
          arr.push(a[i]);
          for (let j = i * 2; j < z.length; j++) {
            arr.push(z[j]);
            count++
            if (count > 1) {
                if (z[j+1] !== undefined && a[i+1] === undefined) {
                for (let k = j+1; k < z.length; k++) {
                  arr.push(z[k])
                }
              }
            break;
            }
          }
        }
    console.log(arr);
    // ["y", "x", "x", "y", "x", "x", "x"]
    
        8
  •  0
  •   SNag    8 年前

    您根本不需要嵌套循环。这可以通过一个带有两个计数器的循环来完成。

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    let result = [];
    
    for(let i = 0, j = 0; i < a.length, j < z.length; i++, j+=2) {
    	result.push(a[i], z[j], z[j+1]);
    }
    
    result = result.filter(item => item !== undefined);
    
    console.log(result);

    下面是压缩成一行核心的相同代码:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    let result = [];
    
    for(let i = 0, j = 0; i < a.length, j < z.length; i++, j+=2) {
    	result.push.apply(result, [a[i], z[j], z[j+1]].filter(m => m !== undefined));
    }
    
    console.log(result);
        9
  •  0
  •   Nina Scholz    8 年前

    您可以获取长度并计算用于拼接和推送到结果集的数组的间隔/部分长度。

    function getX(a, b) {
        var iA = Math.ceil(a.length / b.length),
            iB = Math.ceil(b.length / a.length),
            pA = 0,
            pB = 0,
            result = [];
    
        while (pA < a.length || pB < b.length) {
            result.push(
                ...a.slice(pA, pA += iA),
                ...b.slice(pB, pB += iB)
            );
        }
        return result;
    }
    
    console.log(getX(['y','y','y'], ['x','x','x','x','x']).join(' '));
    console.log(getX(['y','y'], ['x','x','x','x','x']).join(' '));
        10
  •  0
  •   dziraf    8 年前

    下面是一个使用 Array.prototype.reduce() 以及 destructuring assignment :

    let a = ["y", "y", "y"];
    let z = ["x", "x", "x", "x", "x"];
    
    let y = a.reduce((acc, current, index) => {
      return [...acc, current, ...z.splice(0, a[index + 1] ? 2 : z.length)];
    }, []);
    
    console.log(y);
    console.log(z);

    在每个 a 获取先前累积数组的数组元素(最初 [] ),添加 current 元素和两个元素 z 如果 一 有下一个元素或其他 z轴 元素如果 现在的 是 一 . 很遗憾,这会从 z轴 在这个过程中,因此您可能希望在运行之前复制它,也就是说,您可以在函数中包装reduce并传递 z轴 :

    let a = ["y", "y", "y"];
    let z = ["a", "b", "c", "d", "e", "f", "g"];
    
    const interweave = (arr1, arr2) => {
      return arr1.reduce((acc, current, index) => {
        return [
          ...acc,
          current,
          ...arr2.splice(0, arr1[index + 1] ? 2 : arr2.length)
        ];
      }, []);
    };
    
    console.log(interweave(a, [...z]));
    console.log(z);
        11
  •  0
  •   Hassan Sadeghi    8 年前

    你可以不用 for 或 while 我也是!试试这个:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    console.log(
        [].concat.apply([], a.map(function(m, i){return [m].concat(z.slice(i*2, i*2+2));}))
    );

    现在,如果希望这样,可以加入结果:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    console.log(
        [].concat.apply([], a.map(function(m, i){return [m].concat(z.slice(i*2, i*2+2));})).join(",")
    );

    或者如果你喜欢 reduce 函数,您可以尝试:

    let a = ['y','y','y'];
    let z = ['x','x','x','x','x'];
    console.log(
      a.reduce(function(ac, m, i){return ac.push.apply(ac, [m].concat(z.slice(i*2, i*2+2))), ac;}, [])
    );