從給定點開始,從陣列中獲取 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 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始使用
廣告