Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

마지막으로 주어진 요소 수를 배열 JavaScript 앞으로 이동

<시간/>

예를 들어 숫자 n(n <=함수가 사용되는 배열의 길이)을 취하는 prependN()과 같이 배열 함수를 작성해야 하고 끝에서 n개의 요소를 가져와 배열의 맨 앞에 놓습니다.

이 작업을 제자리에서 수행해야 하며 함수는 작업의 성공적인 완료 또는 실패를 기반으로 하는 부울만 반환해야 합니다.

예를 들어 -

// if the input array is:
const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
// and the number n is 3,
// then the array should be reshuffled like:
const output = ["yellow", "magenta", "cyan", "blue", "red", "green",
"orange"];
// and the return value of function should be true

이제 이 함수의 코드를 작성해 보겠습니다 -

예시

const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
Array.prototype.reshuffle = function(num){
const { length: len } = this;
   if(num > len){
      return false;
   };
   const deleted = this.splice(len - num, num);
   this.unshift(...deleted);
   return true;
};
console.log(arr.reshuffle(4));
console.log(arr);

출력

콘솔의 출력은 다음과 같습니다. -

true
[
   'orange', 'yellow',
   'magenta', 'cyan',
   'blue', 'red',
   'green'
]