如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短