未捕获的SyntaxError:意外的令牌'?'

时间:2019-09-28 08:59:43

标签: javascript

console.log(undefined ?? 'default');

为什么会收到错误消息Uncaught SyntaxError:意外令牌'?'

3 个答案:

答案 0 :(得分:2)

当前,javascript中没有??运算符。

您可以使用ternary运算符:

var x = undefined; 
console.log(x == undefined ? 'default' : x);

如果未定义'default',将打印x,否则将打印x的值。

但是,您已经找到了nullish coalescing运算符的建议。目前这是第3阶段的提案,但看起来它将成为ECMAScript的未来版本。

答案 1 :(得分:0)

您也可以使用||运算符..与??相同(对于其他语言)

In js ?? exist but it's a little bit strange cause is the opposite of || ..

so it test if NOT undefined or NULL then do the right ..

所以尝试:

console.log(undefined || 'default')

答案 2 :(得分:0)

如@Uncle的评论中所述,该功能目前仅是一个建议,目前尚未在Javascript中实现。要在现代浏览器中实现它之前使用它,您需要添加以下Babel插件:@babel-plugin-proposal-nullish-coalescing-operator