如何在 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