未捕获的SyntaxError:队列中的意外令牌var
我在JS中实现队列,但控制台保持siplaying Uncaught SyntaxError:意外的令牌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;
}
};
};
将var从
push: function(var elem){
事实上,在JavaScript中,您不需要(也不必 )提供函数参数的类型,因为它是静态类型语言(请参阅函数参数的设置类型?)
另外,要比较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
push: function(var elem){
删除var
链接地址: http://www.djcxy.com/p/46001.html