如何在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' ]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语