먼저 세 개의 인수를 취하는 배열 함수(Array.prototype.get())를 작성해야 합니다. 숫자 n, 두 번째도 숫자, 예를 들어 m, (m <=배열 길이-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 ]