기초공사 (html,css,javascript)

splice와 indexOf예제 본문

academy/JavaScript

splice와 indexOf예제

에스프레소라떼 2024. 5. 20. 13:03

//

const arr6 = [1, 2, 3, 1, 2];

function remove(array, item) {
  const index = array.indexOf(item);
  //item 2 --> 1
  //item 10 -> -1
  console.log(index);

  if (index != -1) array.splice(index, 1);
  //item 2-->array.indexOf(2)--> 2라는 요소가 처음에 1번쨰에 있으므로 변수 index는 1이다.
  // 1과 -1이 같지 않다면--같지않지 - array.splice(1,1)
  // 1부터 한개 지우면 남는것이 [1 3 1 2]

  // item 10 --> array.indexOf(10)->10이라는 요소가 없다. index =-1이다.
  // -1과 -1은 거짓이므로 return array --> 위에서 splice는 원본배열에서 삭제되는것이므로
  // 원본 배열은  [1,3,1,2]가 된다.
  // console.log(remove(arr6, 10));에서는 10이 없으므로 원본배열 그대로 출력된다.
  return array;
}
console.log(remove(arr6, 2)); // [1, 3, 1, 2]
console.log(remove(arr6, 10)); // [1, 3, 1, 2]

 

위의 코드에 자세히 주석처리 해놨다.

이코드를 보면 splice와 indexOf를 이해하는 거임.