如何在 JavaScript 中将多个元素移动到数组的开头?
javascriptweb developmentobject oriented programming更新于 2025/10/3 4:28:17
我们必须编写一个函数,该函数以数组和任意数量的字符串作为参数。任务是检查字符串是否出现在数组中。如果出现,我们必须将该特定字符串移动到数组的前面。
因此,让我们编写该函数的代码 −
示例
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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

