JavaScript에서 스택 및 배열의 Peek 작업
4542 단어 javascript
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에 있는 이 예제를 참조하십시오.
😃 유용하셨다면 공유해 주세요.
Reference
이 문제에 관하여(JavaScript에서 스택 및 배열의 Peek 작업), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/melvin2016/peek-operation-in-stacks-and-arrays-in-javascript-15n8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)