未捕获的SyntaxError:队列中出现意外的令牌变量

时间:2016-05-05 11:01:23

标签: javascript queue

我在JS中实现了队列,但是控制台一直在使用Uncaught SyntaxError:Unexpected token var。我使用了一些在线调试器,它在第21行指出错误。这是代码:

var queue = function (){

var elements = [];
var cur_element = 0;
var del_elem = 0;
return {
    size: function() {
        return cur_element-del_elem;
    },
    empty: function() {
        return cur_element == 0;
    },
    front: function() {
        if(!this.empty()){
            return elements[0];
        }
        return false;
    },
    back: function() {
        if(!this.empty()){
            return elements[cur_element];
        }
        return false;
    },
    push: function(var elem){
        cur_element++;
        elements[cur_element]=elem;
    },
    pop: function() {
        var outcome = elements[del_elem];
        delete elements[del_elem];
        del_elem++;
        return outcome;
    }
    };
};

2 个答案:

答案 0 :(得分:0)

push: function(var elem){

删除var

答案 1 :(得分:0)

从以下地址删除var:

push: function(var elem){

事实上,在javascript中你不需要(并且你一定不能)来提供函数参数的类型,因为它是一种静态类型的语言(参见Set type for function parameters?

另外,要与0进行比较,请使用===代替==,请查看此参考:

http://dorey.github.io/JavaScript-Equality-Table/?utm_content=buffer4f1b9

所以,替换:

return cur_element == 0;

使用:

return cur_element === 0;

(请注意:更换==使用===不是强制性而非强烈推荐!)

以下正确代码:

var queue = function (){

var elements = [];
var cur_element = 0;
var del_elem = 0;
return {
    size: function() {
        return cur_element-del_elem;
    },
    empty: function() {
        return cur_element === 0;
    },
    front: function() {
        if(!this.empty()){
            return elements[0];
        }
        return false;
    },
    back: function() {
        if(!this.empty()){
            return elements[cur_element];
        }
        return false;
    },
    push: function(elem){
        cur_element++;
        elements[cur_element]=elem;
    },
    pop: function() {
        var outcome = elements[del_elem];
        delete elements[del_elem];
        del_elem++;
        return outcome;
    }
    };
};

http://jsbin.com/tirevipoba/edit?html,js,output