为什么栈的输出有undefined

新手上路,请多包涵

js代码如下:

    function Stack(){
        let items = [];
        // 各种属性和方法的声明
        this.push = function(element) {
            items.push(element);
        }
        this.pop = function(){
            return items.pop();
        }
        // 返回栈顶元素
        this.peek = function(){
            return items[items.length-1];
        }
        this.isEmpty = function(){
            return items.length == 0;
        }
        this.size = function(){
            return items.length;
        }
        this.clear = function(){
            items = [];
        }
        this.print = function(){
            console.log(items.toString());
        }
    }
    
    let st = new Stack();
    console.log(st.isEmpty());
    st.push(1);
    st.push(2);
    st.push(3);
    console.log(st.peek());
    console.log(st.isEmpty());
    console.log(st.print());
    st.pop();
    console.log(st.print());

输出结果为:
true
3
false
1,2,3
undefined
1,2
undefined

阅读 1.4k
2 个回答

你的print里面已经打印了,外面为什么还要再打印一次?

print方法没有返回值啊,这也有疑问???

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题