编写一个采用数组并将所有零移动到末尾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]
热门推荐
3 怎么说祝福语简短
5 送蛇的祝福语简短
7 祝福语简短古诗词
10 给孙子拜年祝福语简短
11 许愿星姐妹祝福语简短
12 生日牌祝福语英语简短
13 收生日红包祝福语 简短
14 冬至婆婆的祝福语简短
15 对疫情的简短祝福语
16 药店祝福语简短10字
17 结婚喜庆的祝福语简短
18 领证幽默祝福语简短