比方说,我们必须编写一个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'
]