Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript 배열에서 임의의 항목을 하나씩 제거하고 배열이 빌 때까지 반복하기

문자열 또는 숫자 리터럴로 이루어진 배열이 주어졌을 때, 배열을 인자로 받아 항목이 남아 있는 동안 매번 임의의 요소를 하나씩 제거하면서 동시에 콘솔에 출력하는 함수 removeRandom()를 만들어야 합니다.

이 작업은 Math.random()으로 임의의 난수를 생성한 뒤, 해당 인덱스의 요소를 Array.prototype.splice()로 제거하고 출력하는 과정을 배열의 길이가 0이 될 때까지 반복하는 방식으로 구현할 수 있습니다.

구현 예제

const arr = ['Arsenal', 'Manchester United', 'Chelsea', 'Liverpool',
'Leicester City', 'Manchester City', 'Everton', 'Fulham', 'Cardiff City'];
const removeRandom = (array) => {
    while(array.length){
      const random = Math.floor(Math.random() * array.length);
      const el = array.splice(random, 1)[0];
      console.log(el);
    }
};
removeRandom(arr);

코드 설명

  • while(array.length): 배열에 항목이 하나라도 남아 있으면 반복을 계속합니다.
  • Math.floor(Math.random() * array.length): 현재 배열 길이 범위 내에서 임의의 정수 인덱스를 생성합니다.
  • array.splice(random, 1)[0]: 해당 인덱스의 요소를 배열에서 제거하고 반환합니다.
  • console.log(el): 제거된 요소를 콘솔에 출력합니다.

콘솔 출력 결과는 다음과 같습니다.

참고 − 무작위(random) 출력이기 때문에 실행할 때마다 결과가 달라질 수 있습니다. 아래는 여러 가지 가능한 출력 중 하나의 예시일 뿐입니다.

실행 결과

Leicester City
Fulham
Everton
Chelsea
Manchester City
Liverpool
Cardiff City
Arsenal
Manchester United