라이브러리

[JAVASCRIPT] arr.shift() / arr.unshift(item) - 배열 첫 요소 제거 및 반환 / 앞에 요소 추가




JavaScript의 arr.shift()와 arr.unshift() 메서드


JavaScript의 Array.prototype 객체에는 여러 메서드가 있습니다. 그 중 arr.shift()와 arr.unshift()는 Array의 첫 번째 요소를 제거하거나 추가하는 메서드입니다.

# arr.shift()


`arr.shift()` 메서드는 Array의 첫 번째 요소를 제거하고, 그 요소를 반환합니다. 만약 Array가 비어 있다면 undefined를 반환합니다.

#hostingforum.kr
javascript

let arr = [1, 2, 3, 4, 5];

console.log(arr.shift()); // 1

console.log(arr); // [2, 3, 4, 5]



# arr.unshift()


`arr.unshift()` 메서드는 Array의 첫 번째 요소를 추가합니다. 추가된 요소는 Array의 길이를 증가시킵니다. 만약 추가할 요소가 없다면 Array의 길이는 그대로 유지됩니다.

#hostingforum.kr
javascript

let arr = [2, 3, 4, 5];

console.log(arr.unshift(1)); // 5

console.log(arr); // [1, 2, 3, 4, 5]



예제: 실생활에서의 사용


실생활에서 이러한 메서드를 사용하는 예를 살펴보겠습니다. 예를 들어, 학생들의 성적을 관리하는 시스템에서, 학생의 성적을 삭제하거나 추가할 때 사용할 수 있습니다.

#hostingforum.kr
javascript

class Student {

  constructor(name, score) {

    this.name = name;

    this.score = score;

  }

}



class StudentSystem {

  constructor() {

    this.students = [];

  }



  addStudent(student) {

    this.students.unshift(student);

  }



  deleteStudent(student) {

    const index = this.students.indexOf(student);

    if (index !== -1) {

      this.students.splice(index, 1);

    }

  }



  printStudents() {

    console.log(this.students);

  }

}



const system = new StudentSystem();

system.addStudent(new Student("John", 90));

system.addStudent(new Student("Jane", 80));

system.printStudents(); // [Student { name: 'John', score: 90 }, Student { name: 'Jane', score: 80 }]

system.deleteStudent(new Student("John", 90));

system.printStudents(); // [Student { name: 'Jane', score: 80 }]



이 예제에서 `addStudent` 메서드는 `unshift` 메서드를 사용하여 학생의 성적을 추가하고, `deleteStudent` 메서드는 `indexOf` 메서드를 사용하여 학생의 인덱스를 찾은 후 `splice` 메서드를 사용하여 학생의 성적을 삭제합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 10 페이지

검색

게시물 검색