使用JavaScript将数组的值交织到位

前端之家收集整理的这篇文章主要介绍了使用JavaScript将数组的值交织到位 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

假设我有一个数字数组=> [1,2,3,4,5,6]

我想将它们交织=> [1,6]

我可以使用以下代码来做到这一点

const nums = [1,6];
const results = [];
nums.slice(0,nums.length / 2).forEach((num,index) => results.push(num,nums.slice(nums.length / 2,nums.length)[index]))
console.log(results);

为了总体上成为一个更好的程序员,我想知道如何就地修改数组,就好像它是一个链表一样,而不必通过增加数组来增加空间复杂性.

我已经写出了逻辑,但似乎无法找到一种模式来创建函数.

// [0] do nothing

// [1]
currentIndex = 1;
temp = nums[3];
nums[3] = nums[currentIndex];
nums[currentIndex] = temp;
// 1[2]3[4]56 => 1[4]3[2]56

// [2]
currentIndex = 2;
temp = nums[3];
nums[3] = nums[currentIndex];
nums[currentIndex] = temp;
// 14[3][2]56 => 14[2][3]56 

// [3]
currentIndex = 3;
temp = nums[4];
nums[4] = nums[currentIndex];
nums[currentIndex] = temp;
// 142[3][5]6 => 142[5][3]6

// while (currentIndex < nums.length / 2) {...}

我在想这个吗?

最佳答案
splice函数可在现有阵列上使用,因此您可以系统地使用它.我添加了注释,以使循环的每一步都清楚发生了什么.

当然,这仅适用于具有偶数个元素的数组.我将它留给您以使其更通用.

var start = [1,6];
var half = start.length / 2;
var x = 1;
for (let i = half; i < start.length; i++) {
  let a = start[i]; 
  // remove the existing element
  start.splice(i,1); 
  // insert it at the right place
  start.splice(x,a); 
  // increment the index of where to insert the next element by two
  x += 2;
}
console.log(start);
原文链接:https://www.f2er.com/js/531146.html

猜你在找的JavaScript相关文章