將 JavaScript 中陣列中的所有零移動到末尾
問題
我們需要編寫一個 JavaScript 函式,該函式接受一個可能包含一些 0 的字面量陣列。我們的函式應該調整該陣列,使所有零都移到末尾,所有非零元素佔據其相對位置。
示例
以下程式碼 −
const arr = [5, 0, 1, 0, -3, 0, 4, 6];
const moveAllZero = (arr = []) => {
const res = [];
let currIndex = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(el === 0){
res.push(0);
}else{
res.splice(currIndex, undefined, el);
currIndex++;
};
};
return res;
};
console.log(moveAllZero(arr));輸出
以下為控制檯輸出 −
[ 5, 1, -3, 4, 6, 0, 0, 0 ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP