为什么逻辑OR不能与JavaScript中的错误一起使用? [英] Why doesn't logical OR work with error throwing in JavaScript?

查看:67
本文介绍了为什么逻辑OR不能与JavaScript中的错误一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一种非常常见且有用的做法:

This is a pretty common and useful practice:

// default via value
var un = undefined
var v1 = un || 1

// default via a function call
var myval = () => 1
var v2 = un || myval()

但是在抛出错误时它不起作用(SyntaxError):

But it doesn't work (SyntaxError) when throwing an error:

var v3 = un || throw new Error('un is not set!')

有没有办法如何实现相同以同样优雅的方式效果?
这是IMHO的很多样板代码:

Is there a way how to achieve the same effect in a similarly elegant way? This is IMHO a lot of boilerplate code:

if (!un) {
    throw new Error('un is not set!')
}
var v3 = un

或者是否有任何理论障碍,为什么这不是,也永远不可能?

Or is there any theoretical obstruction, why this is not, and never will be, possible?

推荐答案

throw 只是语句;它可能不存在于需要表达式的位置。出于类似的原因,你不能在那里放一个 if 语句,例如

throw is a statement only; it may not exist in a position where an expression is required. For similar reasons, you can't put an if statement there, for example

var something = false || if (cond) { /* something */ }

也是无效的语法。

只允许将表达式(评估为值的事物)分配给变量。如果你想抛出,你 抛出作为一个声明,这意味着你不能把它放在作业的右边。

Only expressions (things that evaluate to a value) are permitted to be assigned to variables. If you want to throw, you have to throw as a statement, which means you can't put it on the right-hand side of an assignment.

我想一种方法是在<$右侧使用IIFE c $ c> || ,允许您在该函数的第一行使用语句:

I suppose one way would be to use an IIFE on the right-hand side of the ||, allowing you to use a statement on the first line of that function:

var un = undefined
var v2 = un || (() => { throw new Error('nope') })();

但这很奇怪。我更喜欢显式的如果 - 抛出

But that's pretty weird. I'd prefer the explicit if - throw.

这篇关于为什么逻辑OR不能与JavaScript中的错误一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆