当前位置: 代码迷 >> JavaScript >> 编写我自己的反向数组函数而不定义新的空数组
  详细解决方案

编写我自己的反向数组函数而不定义新的空数组

热度:38   发布时间:2023-06-07 11:21:53.0

我试图编写一个函数,该函数可反转数组的元素,而无需在函数中定义新的空数组。

let arrayValue = [1, 2, 3, 4, 5]

function remove(array, index) {
return array.slice(0, index).concat(array.slice(index + 1));
}

function reverseArrayInPlace(array) {
  for (i = array.length - 2; i >= 0; i--) {
    let removedCharacter = array[i];
    array = array.concat(removedCharacter);
    array = remove(array, i);
  } 
    return array;
}

当我console.log(reverseArrayInPlace(arrayValue))我得到[5,4,3,2,1]的相反顺序。

但是,当我尝试只做reverseArrayInPlace(arrayValue)然后再做console.log(arrayValue)时,我得到的[1、2、3、4、5]是开头定义的值。

有没有一种方法可以更新函数中的arrayValue绑定,然后在函数外为console.log时,显示相反的顺序?

// show cases of even and odd lengths
const x = [1,2,3,4];
const y = [1,2,3,4,5];

for (let i = 0; i < x.length / 2; i++) {
  const tmp = x[i];

  x[i] = x[x.length - 1 - i];
  x[x.length - 1 - i] = tmp;
}

for (let i = 0; i < y.length / 2; i++) {
  const tmp = y[i];

  y[i] = y[y.length - 1 - i];
  y[y.length - 1 - i] = tmp;
}

console.log(x);
// [4, 3, 2, 1]

console.log(y);
// [5, 4, 3, 2, 1]

关于Array的和方法的MDN文档解释说,这些方法返回新数组,而不是修改现有数组。 如果您正在寻找用于修改数组的内置Array方法,则将完成此工作。 但是,使用splice实现此方法将比其他答案所建议的仅使用for循环更为复杂。

您可以围绕数组的中点对称地交换值,例如

 const arr = [0,1,2,3,4]; const len = arr.length; for(let i = 0; i < len/2; i++){ let temp = arr[i]; arr[i] = arr[len-1-i]; arr[len-1-i] = temp; } console.log(arr); 

function reverseArrayInPlace(array) {
 for (let i = 0; i < array.length / 2; i++) {
  const oppositeArrayIndex = array.length - (i + 1);
  const oppasiteArrayValue = array[oppositeArrayIndex];
  array[oppositeArrayIndex] = array[i];
  array[i] = oppasiteArrayValue;
 }
}
  相关解决方案