如何在 JavaScript 中將多個元素移動到陣列的開頭?
我們必須編寫一個函式,該函式採用陣列和任意數量的字串作為引數。任務是檢查字串是否出現在陣列中。如果出現,我們必須將該特定元素移動到陣列的前面。
因此,讓我們為這個函式編寫程式碼 −
示例
const arr = ['The', 'weather', 'today', 'is', 'a', 'bit', 'windy.'];
const pushFront = (arr, ...strings) => {
strings.forEach(el => {
const index = arr.indexOf(el);
if(index !== -1){
arr.unshift(arr.splice(index, 1)[0]);
};
});
};
pushFront(arr, 'today', 'air', 'bit', 'windy.', 'rain');
console.log(arr);輸出
控制檯中的輸出將是 −
[ 'windy.', 'bit', 'today', 'The', 'weather', 'is', 'a' ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP