将最后给定数量的元素移到数组JavaScript的前面
比方说,我们必须编写一个Array函数,假设prependN()它接受一个数字n(n<=与该函数一起使用的数组的长度),并且从头开始取n个元素并将它们放在数组的前面。
我们必须就地执行此操作,并且函数应仅基于任务成功完成或失败返回布尔值。
例如-
// if the input array is: const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; //并且数字n为3, //那么应该像这样重新排列数组: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // and the return value of function should be true
现在,让我们编写此函数的代码-
示例
const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
Array.prototype.reshuffle = function(num){
const { length: len } = this;
if(num > len){
return false;
};
const deleted = this.splice(len - num, num);
this.unshift(...deleted);
return true;
};
console.log(arr.reshuffle(4));
console.log(arr);输出结果
控制台中的输出将为-
true [ 'orange', 'yellow', 'magenta', 'cyan', 'blue', 'red', 'green' ]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿