JavaScript变量被忽略 [英] JavaScript variable being ignored
问题描述
因此,我正在尝试使用JS编写数据结构可视化工具(以便可以在线托管)。好像我的JS忽略了我的变量(并声称某些功能不存在),我不知道为什么。非常感谢您的帮助。
So I'm trying to write a Data Structures Visualizer with JS (so that I can host it online). It seems as though my JS ignoring my variables (and claiming some functions don't exist) and I can't figure out why. I'd appreciate the help.
var stack = new Stack();
var defaultValueCounter = 0;
function push() {
var value = document.getElementById("add").value;
if (value === "") {
defaultValueCounter++;
value = defaultValueCounter;
}
//console.log(stack + ", " + value)
stack.push(value);
addCol(value);
stack.print();
document.getElementById("add").value = "";
}
在该代码中,由于某种原因似乎忽略了堆栈(初始化为undefined )。我已经通过将声明移到push()函数中来测试了这个假设,并且它起作用了(尽管出于显而易见的原因,我的Stack只能包含1个元素)。我该怎么解决
In that code, it seems to ignore stack for some reason (initializes to undefined). I've tested this hypothesis by moving the declaration inside the push() function, and it works (although for obvious reasons, my Stack can only contain 1 element). What can I do to fix it
编辑:
共享我的堆栈实现
Sharing my Stack implementation
function Node() {
this.value;
this.next ;
}
var Stack= function(){
this.head;
}
Node.prototype.insert=function(value) {
var current = this;
if (current.value === undefined) { //has nothing yet
current.value = value; //insert here
return;
}
if(current.next === undefined) { //completely null
current.next = new Node();//want new node
}
var c = current.next;
c.insert(value);
}
Stack.prototype.push= function(value) {
if(value==undefined || value==""){
throw "Please input proper value (number)"
}
if(this.head==undefined){//nothing exists yet
this.head=new Node();
this.head.value=value;
}else{//nonempty stack
var c=this.head;
c.next=new Node();
c.next=this.head;
c.value=value;
this.head=c;
}
}
Stack.prototype.top= function() {
if(this.head==undefined){//nothing exists yet
throw "Trying to get top of null"
}else{//nonempty stack
return this.head.value;
}
}
Stack.prototype.pop= function() {
if(this.head==undefined){//nothing exists yet
throw "Trying to get top of null"
}else{//nonempty stack
var val=this.head.value;
this.head=this.head.next;
return val;
}
}
Stack.prototype.print= function(){
//debugging purposes
var c=new Node();
c.value=this.head.value
c.next=this.head.next
while(c.value!=undefined){
console.log(c.value)
c=c.next
}
console.log("Head: "+ this.value)
}
编辑:似乎代码没有在开始时初始化栈。我该怎么解决?
It seems as though the code is not initializing the stack at the beginning. What can I do to resolve this?
推荐答案
出于某种原因,我通过删除top()解决了所有问题。不知道为什么。会进一步调查我的代码
For some reason, I resolved all issues by deleting top(). Not sure why. Will investigate my code futher
这篇关于JavaScript变量被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!