将最后给定数量的元素移到数组 JavaScript 的前面
javascriptweb developmentobject oriented programming更新于 2025/10/21 23:08:17
假设,我们必须编写一个数组函数,即 prependN(),它接受一个数字 n(n <= 函数使用的数组的长度),并从末尾获取 n 个元素并将它们放在数组的前面。
我们必须在现场执行此操作,并且该函数应仅根据任务成功完成或失败返回布尔值。
例如 −
// 如果输入数组是: const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; // 并且数字 n 是 3, // 那么数组应该重新排列如下: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // 并且函数的返回值应该为 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' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

