编写一个采用数组并将所有零移动到末尾JavaScript的算法
我们必须编写一个函数,该函数接受一个数组并将该数组中存在的所有零移动到该数组的末尾,而无需使用任何额外的空间。我们将在这里使用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]