Uncaught SyntaxError: Unexpected token var in queue

I was implementing queue in JS, but the console keeps siplaying Uncaught SyntaxError: Unexpected token var. I used some online debugger and it points error in line 21. This is the code:

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;
    }
    };
};

remove var from:

push: function(var elem){

In fact, in javascript you don't need (and you mustn't ) to provide the type of a function parameter because it is a statically typed language (see Set type for function parameters?)

Also, to compare with 0, please use === instead of == , check this for reference:

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

So, replace:

return cur_element == 0;

with:

return cur_element === 0;

(PLEASE NOTE: REPLACING == WITH === WAS NOT MANDATORY BUT HIGHLY RECOMMENDED!)

Correct code below:

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


push: function(var elem){

删除var

链接地址: http://www.djcxy.com/p/46002.html

上一篇: 未捕获的SyntaxError:意外的标记<进入DOCTYPE html PUBLIC

下一篇: 未捕获的SyntaxError:队列中的意外令牌var