JavaScript에서 스택 및 배열의 ​​Peek 작업

4542 단어 javascript
Originally posted here!
peek() 메서드는 배열의 마지막 요소만 보거나 스택 데이터 구조에서 최근에 추가된 요소를 보는 데 사용됩니다.

안타깝게도 peek() 개체에는 Array라는 메서드가 없습니다. JavaScript로 직접 구현해야 합니다.

우리가 해야 할 일은 마지막 요소를 가져오지만 제거하지 않는 것뿐입니다.

이런식으로 할 수 있는데,

const lastElement = array[array.length - 1];


그러나 이것을 Array 객체에 메소드로 추가하려면 이것을 Array 프로토타입 체인에 메소드로 추가해야 합니다.
peek() 프로토타입 체인에 Array 메서드를 추가해 보겠습니다.

// Adding peek method to the Array
// prototype chain
Array.prototype.peek = function () {
  if (this.length === 0) {
    throw new Error("out of bounds");
  }
  return this[this.length - 1];
};


함수는 먼저 배열의 길이가 0인지 확인하고, 길이가 true이면 오류를 생성하고, false이면 마지막 요소를 반환합니다.

이제 peek() , push() 배열 메서드를 사용하는 것처럼 pop() 메서드를 사용할 수 있습니다.

// Adding peek method to the Array
// prototype chain
Array.prototype.peek = function () {
  if (this.length === 0) {
    throw new Error("out of bounds");
  }
  return this[this.length - 1];
};

// array
const arr = [1, 2, 3, 4, 5, 6];

// peek() method
const element = arr.peek();
console.log(element); // 6


JSBin에 있는 이 예제를 참조하십시오.

😃 유용하셨다면 공유해 주세요.

좋은 웹페이지 즐겨찾기