编写一个算法,该算法接受一个数组并将所有零移动到末尾 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/2 19:56:17

我们必须编写一个函数,该函数接受一个数组并将该数组中存在的所有零移动到数组末尾,而不使用任何额外空间。我们将在这里使用 Array.prototype.forEach() 方法以及 Array.prototype.splice() 和 Array.prototype.push()。

该函数的代码将是 −

示例

const arr = [34, 6, 76, 0, 0, 343, 90, 0, 32, 0, 34, 21, 54];
const moveZero = (arr) => {
   for(ind = 0; ind < arr.length; ind++){
      const el = arr[ind];
      if(el === 0){
         arr.push(arr.splice(ind, 1)[0]);
         ind--;
      };
   }
};
moveZero(arr);
console.log(arr);

输出

控制台中的输出将是 −

[34, 6, 76, 343, 90, 32, 34, 21, 54, 0, 0, 0, 0]

相关文章


有用资源