Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thêm (push) phần tử vào Stack trong JavaScript

Xét lớp Stack với helper functions:

Ví dụ - Lớp Stack cơ bản

class Stack {    constructor(maxSize) {       if (isNaN(maxSize)) {          maxSize = 10;       }       this.maxSize = maxSize;       this.container = [];    }    display() {       console.log(this.container);    }    isEmpty() {       return this.container.length === 0;    }    isFull() {       return this.container.length >= maxSize;    } }

Thêm thao tác PUSH: thêm phần tử vào đỉnh (cuối mảng container).

Ví dụ

push(element) {    if (this.isFull()) {       console.log("Stack Overflow!");       return;    }    this.container.push(element); }

Kiểm tra:

Ví dụ

let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();

Kết quả

[] Stack Overflow! [ 10, 20 ]

Stack size 2: push 10,20 thành công, push 30 báo Overflow, stack vẫn [10,20].