Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy n số từ mảng bắt đầu từ điểm cho trước JavaScript

Viết phương thức mảng Array.prototype.get() nhận 3 tham số: số n, chỉ số m (m ≤ length-1), hướng 'left' hoặc 'right'. Trả về mảng con n phần tử bắt đầu từ chỉ số m theo hướng chỉ định.

Ví dụ:

// arr = [0,1,2,3,4,5,6,7]// arr.get(4, 6, 'right') → [6, 7, 0, 1]

Ví dụ

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'));

Kết quả

Đầu ra trong console sẽ là:

[ 6, 7, 0, 1 ][ 6, 5, 4, 3, 2, 1, 0, 7, 6 ]