从给定点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 ]
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短