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

javascriptweb developmentobject oriented programming更新于 2025/10/22 3:24:17

我们必须编写一个数组函数 (Array.prototype.get()),它接受三个参数:第一个参数是数字 n,第二个参数也是一个数字,比如 m,(m <= 数组长度-1),第二个参数是一个字符串,它可以有两个值 − ‘left’ 或 ‘right’。

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

例如 −

// 如果数组是:
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
]

相关文章


有用资源