Javascriptでスタックの要素をクリアする
例
class Stack {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
// A method just to see the contents while we develop this class
display() {
console.log(this.container);
}
// Checking if the array is empty
isEmpty() {
return this.container.length === 0;
}
// Check if array is full
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
peek() {
if (isEmpty()) {
console.log("Stack Underflow!");
return;
}
return this.container[this.container.length - 1];
}
} ここでisFull 関数は、コンテナの長さがmaxSize以上であるかどうかをチェックし、それに応じて返します。 isEmpty 関数は、コンテナのサイズが0であるかどうかをチェックします。プッシュ関数とポップ関数は、それぞれスタックに新しい要素を追加したり、スタックから新しい要素を削除したりするために使用されます。
このセクションでは、このクラスにCLEAR操作を追加します。コンテナ要素を空の配列に再割り当てするだけで、内容をクリアできます。たとえば、
例
clear() {
this.container = [];
} この関数が正常に機能しているかどうかは、-
を使用して確認できます。例
let s = new Stack(2); s.push(10); s.push(20); s.display(); s.clear(); s.display();
出力
これにより、出力が得られます-
[10, 20] []
-
JavaScriptを使用して同じ配列内の配列の要素を複製するにはどうすればよいですか?
以下は、同じ配列内の配列の要素を複製するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" > <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nbs
-
JavaScriptでのスタックの実装
以下は、JavaScriptでスタックを実装するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>