我正在尝试将函数值存储在变量中,并希望在文本区域t1
中显示内容。
因此,每次推送值时,我都可以在变量s
中获取print函数,并可以在textarea t1
中显示内容。
<html>
<head>
<title>Stack With Constructor </title>
</head>
<body>
<div>Stack </div>
<div>
<h1>stack</h1>
<h2>Stage1.</h2>
<p id="p1">
stack
</p>
<textarea id="t1"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
</div>
<textarea id="t"></textarea>
<script>
function push(v) {
if (this.st === 0) {
console.log("Stack Overflow");
} else {
this.st = this.st - 1;
this.stk[this.st] = v;
}
}
function pop() {
if (this.st === 10) {
console.log("Stack Underflow");
} else {
var temp = this.stk[this.st];
this.st = this.st + 1;
return temp;
}
}
function print() {
console.log("Printing Stack");
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
}
};
function MyStack() {
this.st = 10;
this.stk = new Array(10);
this.push = push;
this.pop = pop;
this.print = print;
};
var s1 = new MyStack();
function doJob() {
var x=document.getElementById("t").value;
s1.push(x);
var s=s1.print();
document.getElementById("t1").value=s;
}
</script>
</body>
</html>
我想在文本区域t1
中显示打印功能,以便它可以作为交互式堆栈。
当我尝试推送价值时,我在textarea中获得undefined
。
答案 0 :(得分:1)
更改您的打印功能,如
function print() {
console.log("Printing Stack");
var str = "";//empty string
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
str+=this.stk[i]+'\n';//concatenate the value and a new line
}
return str;
};
<强>样本强>
<html>
<head>
<title>Stack With Constructor </title>
</head>
<body>
<div>Stack </div>
<div>
<h1>stack</h1>
<h2>Stage1.</h2>
<p id="p1">
stack
</p>
<textarea id="t1"></textarea>
<button onclick="doJob()">push</button>
<button onclick="doJob1()">pop</button>
</div>
<textarea id="t"></textarea>
<script>
function push(v) {
if (this.st === 0) {
console.log("Stack Overflow");
} else {
this.st = this.st - 1;
this.stk[this.st] = v;
}
}
function pop() {
if (this.st === 10) {
console.log("Stack Underflow");
} else {
var temp = this.stk[this.st];
this.st = this.st + 1;
return temp;
}
}
function print() {
console.log("Printing Stack");
var str = "";//empty string
for (var i = this.st ; i < 10; i++) {
console.log(this.stk[i]);
str+=this.stk[i]+'\n';//concatenate the value and a new line
}
return str;
};
function MyStack() {
this.st = 10;
this.stk = new Array(10);
this.push = push;
this.pop = pop;
this.print = print;
};
var s1 = new MyStack();
function doJob() {
var x=document.getElementById("t").value;
s1.push(x);
var s=s1.print();
document.getElementById("t1").value=s;
}
function doJob1(){
s1.pop();
var s=s1.print();
document.getElementById("t1").value=s;
}
</script>
</body>