-3

试图找到这个堆栈的最小值;但是,每当我在 JSFiddle 中运行它时,什么都不会打印出来……有人向我解释为什么?这是代码:

function min_stack() {
var min = 0; 
this.elements = [];

this.push = function(element) {
    this.elements.push(element);
}

this.pop = function() {
    return this.elements.pop();
}

this.min = function() {
    min = this.elements[0]; 
    if (this.elements.length > 0) {
        for(int i = 0; i < this.elements.length; i++) {
            if (min > this.elements[i]) {
                min = this.elements[i]; 
            }
        }
    }
    return min; 
   }    

}

var myStack = new min_stack();
myStack.push(5);
myStack.push(4);
myStack.push(3);
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
4

2 回答 2

2

您的语法错误会for立即显示在浏览器控制台中

改变:

for(int i = 0; i < this.elements.length; i++) { 

for(var i = 0; i < this.elements.length; i++) { 

演示:http: //jsfiddle.net/y7wET/

也正如评论中指出的那样,我怀疑你想使用print

于 2012-12-25T05:43:50.663 回答
1

int i = 0;不是有效的 JavaScript。JavaScript 不允许在声明变量时指定变量的类型;相反,使用var i = 0;.

此外,因为“window”是全局对象,所以在网页上下文中,print() 等效于window.print(),它将页面打印到您的打印机。

For debugging purposes, you can pop up a message box using window.alert(); if that is too annoying, you could do something such as adding your output to a textarea element instead.

于 2012-12-25T05:47:26.507 回答