编写一个采用数组并将所有零移动到末尾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]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短