为什么逻辑OR不能与JavaScript中的错误一起使用?

编程入门 行业动态 更新时间:2024-10-26 15:27:10
本文介绍了为什么逻辑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.

我想一种方法是在 || ,允许您在该函数的第一行使用语句:

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中的错误一起使用?

本文发布于:2023-10-30 18:53:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能与   逻辑   错误   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!