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

时间:2018-09-25 05:42:41

标签: javascript loops

我非常想让它运行,因为嵌套循环对我来说还是有点有趣。

具有以下两个数组:

def palindrome(string)
      string.downcase.split(/\W+/).join('') == . 
      string.downcase.split(/\W+/).join('').reverse ? 'yes is a palindrome' : ' is not a palindrome. :('
    end

# test code

p palindrome("Dennis, Nell, Edna, Leon, Nedra, Anita, Rolf, Nora, Alice, Carol, Leo, Jane, Reed, Dena, Dale, Basil, Rae, Penny, Lana, Dave, Denny, Lena, Ida, Bernadette, Ben, Ray, Lila, Nina, Jo, Ira, Mara, Sara, Mario, Jan, Ina, Lily, Arne, Bette, Dan, Reba, Diane, Lynn, Ed, Eva, Dana, Lynne, Pearl, Isabel, Ada, Ned, Dee, Rena, Joel, Lora, Cecil, Aaron, Flora, Tina, Arden, Noel, and Ellen sinned.")
p palindrome("Depardieu, go razz a rogue I draped")
p palindrome("Desserts I stressed.")
p palindrome("Detartrated.")
p palindrome("Devo met a Mr., eh, DNA and her mate moved.")
p palindrome("Di as dad said.")
p palindrome("Did I draw Della too tall, Edward? I did?")
p palindrome("Dior droid.")
p palindrome("DNA-land.")
p palindrome("Do geese see god?")
p palindrome("Do good? I? No. Evil anon I deliver. I maim nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I. Lo! Rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. Reviled, I (Nona) live on. I do, O God.")
p palindrome("abracadabra!")
p palindrome("Mister, mister, on a see-saw with your sister.")
p palindrome("Almost every sentence is NOT a palindrome! How unfair!")

如何从a 打印一个值,然后从z打印两个值,依此类推?

"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
"yes is a palindrome"
" is not a palindrome. :("
" is not a palindrome. :("
" is not a palindrome. :("

如果值改为:

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

它将打印:

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

这是我到目前为止尝试过的:

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

11 个答案:

答案 0 :(得分:0)

`
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;
    }
  }
}`

尝试这个。

答案 1 :(得分:0)

我修复了您的循环:

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)

您拥有的一种选择是使用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

答案 3 :(得分:0)

  let aIndex = 0, zIndex = 0;

 while(aIndex < a.length || zIndex < z.length) {
    console.log(
      a[aIndex++],
      z[zIndex++],
      z[zIndex++]
   );
 }

答案 4 :(得分:0)

这是非破坏性的方式

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; }
        }

      }
    }

答案 5 :(得分:0)

您也可以不使用任何forwhile来做到这一点!试试这个:

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;}, [])
);

答案 6 :(得分:0)

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)

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

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);

答案 8 :(得分:0)

请看下面的代码。我将您的预期输出结果放入数组。

    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"]

答案 9 :(得分:0)

以下是使用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元素和a中的两个元素元素或z个元素的其余部分(如果currenta的最后一个元素)。 不幸的是,此操作会从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);

答案 10 :(得分:0)

您可以获取长度并计算数组的间隔/部分长度,以进行拼接并推入结果集。

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(' '));