从给定点JavaScript开始从数组中获取n个数字
我们必须编写一个数组函数(Array.prototype.get()),该函数首先接受三个参数,一个数字n,第二个也是数字,例如m,(m<=数组长度-1),第二个是字符串可以具有两个值之一-“left”或“right”。
该函数应返回原始数组的子数组,该子数组应包含从索引m开始的n个元素,并且在指定的方向上(如left或right)。
例如-
// if the array is: const arr = [0, 1, 2, 3, 4, 5, 6, 7]; //函数调用是: arr.get(4, 6, 'right'); //那么输出应该是: const output = [6, 7, 0, 1];
因此,让我们编写此函数的代码-
示例
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
Array.prototype.get = function(num, ind, direction){
const amount = direction === 'left' ? -1 : 1;
if(ind > this.length-1){
return false;
};
const res = [];
for(let i = ind, j = 0; j < num; i += amount, j++){
if(i > this.length-1){
i = i % this.length;
};
if(i < 0){
i = this.length-1;
};
res.push(this[i]);
};
return res;
};
console.log(arr.get(4, 6, 'right'));
console.log(arr.get(9, 6, 'left'));输出结果
控制台中的输出将为-
[ 6, 7, 0, 1 ] [ 6, 5, 4, 3, 2, 1, 0, 7, 6 ]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿