編寫一個演算法,該演算法接受一個數組並將 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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP