从给定点开始,从数组中获取 n 个数字 JavaScript


我们必须编写一个数组函数 (Array.prototype.get()),它接收三个参数:第一个参数是一个数字 n,第二个也是一个数字,m,(m<= array length-1),第二个是一个可以具有这两个值之一的字符串 -‘left’或‘right’。

该函数应返回原始数组的一个子数组,其中应包含从索引 m 开始的 n 个元素,并以指定的方向(例如向左或向右)排列。

例如 -

// if the array is:
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
// and the function call is:
arr.get(4, 6, 'right');
// then the output should be:
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
]

更新于: 28-8-2020

235 次浏览

开启你的 职业生涯

完成课程并获得认证

开始使用
广告
© . All rights reserved.