从两个数组交替取值并放入一个新的第三个数组

3
我正在学习JavaScript的第三周,现在遇到了一个有些棘手的任务。
我的任务是创建一个名为mix的函数,它需要两个参数,都是数组。当调用该函数时,应返回一个新的列表,该列表在这两个先前的数组之间交替(见下面的示例)。
由于涉及到数组和循环,所以我必须使用这些。另外,我只能使用以下数组函数:push、pop、shift和unshift。
我的老师说,使用while循环最容易解决这个问题。
示例:
mix([], []) === []

mix([2, 4], []) === [2, 4]

mix([], [8, 16]) === [8, 16]

mix([1, 3, 5], [2, 4]) === [1, 2, 3, 4, 5]

mix([10, 9], ['a', 'b', 'c']) === [10, 'a', 9, 'b', 'c']

在我得到有关使用 while 循环最简单的提示之前,我开始尝试使用 for 循环。我在这里遇到的问题是只有在数组长度相同时它才能正常工作,但我不知道如何解决让数组长度可以不同的问题。

由于我想要学习,所以我希望能得到正确方向的指引而不是整个答案!

请原谅我的混乱初学者代码 :)

我当前的代码

function mix(array1, array2) {
    let newList = [];
    for(i = 0; i < array1.length || i < array2.length; i++) {
        if(array1.length > 0 || array2.length > 0){
            newList.push( array1[i] );
            newList.push( array2[i] );
            
        }
        
    }
    return newList;
}   
mix([10, 9],['a', 'b', 'c'])

我也想知道使用while循环会更容易些,以及该如何使用它。谢谢!

3
你距离解决方法并不远。我的最佳建议是直接向你的老师提问,他的工作就是教导你。 - Cid
4个回答

4
为了修复您现有的代码,您需要分别检查 i < array1.length(如果是,则推送array1 [i]),并且还需要对array2 进行类似的测试。

function mix(array1, array2) {
  let newList = [];
  for (let i = 0; i < array1.length || i < array2.length; i++) {
    if (i < array1.length) {
      newList.push(array1[i]);
    }
    if (i < array2.length) {
      newList.push(array2[i]);
    }
  }
  return newList;
}
console.log(mix([10, 9], ['a', 'b', 'c']));

请确保使用 let i 声明变量 i,否则会隐式创建全局变量(或在严格模式下抛出错误)。

使用 while 循环进行此操作,应该循环长度为任意一个数组的条件,然后从它们中 shift (即移除第一个元素):

function mix(array1, array2) {
  const newList = [];
  while (array1.length || array2.length) {
    if (array1.length) {
      newList.push(array1.shift());
    }
    if (array2.length) {
      newList.push(array2.shift());
    }
  }
  return newList;
}
console.log(mix([10, 9], ['a', 'b', 'c']));


非常感谢!这解决了一切。现在有它在我面前时,让人讨厌的是它看起来多么明显。:D - Poze

0

另一种方法是将输入数组视为二维数组。

然后,您可以:

  1. 旋转/转置二维数组(行变为列);以及
  2. 展平结果(行连接成一维数组)。

对于示例输入[1, 3, 5],[2, 4],转换如下:

              Rotate             Flatten
[1, 3, 5],      ⇒      [1, 2],      ⇒      [1, 2, 3, 4, 5]
[2, 4]                 [3, 4],
                       [5]

或者,在代码中:

const mix = (...arrays) => {
  const transposed = arrays.reduce((result, row) => {
    row.forEach((value, i) => result[i] = [...result[i] || [], value]);
    return result;
  }, []);
  return transposed.flat();
};


console.log(mix([], [])); // === []
console.log(mix([2, 4], [])); // === [2, 4]
console.log(mix([], [8, 16])); // === [8, 16]
console.log(mix([1, 3, 5], [2, 4])); // === [1, 2, 3, 4, 5]
console.log(mix([10, 9], ['a', 'b', 'c'])); // === [10, 'a', 9, 'b', 'c']

这种方法的好处是它能自动缩放以允许超过两个输入数组,并且不像移位操作,不会改变输入数组。


0

你可以使用数组的 shift 方法做得更好,它会取出数组的第一个元素并返回其值,例如:

const firstElement = [1, 2, 4].shift();
// firstElement - 1
// array [2, 4]

有了这些信息,现在你可以像这样编写你的函数:

function (arr1, arr2) {
   const resultArr = [];
   while(arr1.length && arr2.length) {
       resultArr.push(arr1.shift());
       resultArr.push(arr2.shift());
   }
   return resultArr.concat(arr1, arr2);
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接