我正在使用 node.js
,它是我根据可用说明从其网站安装的 here .我尝试执行“JavaScript - The Good Parts”教科书中的这个例子:
var myObject = {
value: 0;
increment: function (inc) {
this.value += (typeof inc) === 'number' ? inc : 1;
}
};
myObject.increment( );
document.writeln(myObject.value);
myObject.increment(2);
document.writeln(myObject.value);
但是,当我调用 node test.js
(它所在的文件的名称)时,出现以下错误:
value: 0;
^
SyntaxError: Unexpected token ;
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
这是给出的确切示例,这就是为什么我对为什么它不起作用感到困惑。我错过了什么吗?
最佳答案
对象文字键值对使用逗号分隔,而不是分号。而不是这个:
var myObject = {
value: 0;
increment: function (inc) {
this.value += (typeof inc) === 'number' ? inc : 1;
}
};
使用这个:
var myObject = {
value: 0,
increment: function (inc) {
this.value += (typeof inc) === 'number' ? inc : 1;
}
};
关于javascript - 使用带有教科书示例的 node.js 出现意外 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22891285/