尝试/抓住oneliner吗? [英] Try/catch oneliner available?

查看:76
本文介绍了尝试/抓住oneliner吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像您可以转换以下内容一样:

Just as you can convert the following:

var t;
if(foo == "bar") {
    t = "a";
} else {
    t = "b";
}

进入:

t = foo == "bar" ? "a" : "b";

,我想知道是否有一种简写/单行方式将其转换:

, I was wondering if there is a shorthand / oneline way to convert this:

var t;
try {
    t = someFunc();
} catch(e) {
    t = somethingElse;
}

是否有一种简便的方法,最好是单线?我当然可以删除换行符,但是我的意思是像if? :一样.

Is there a method of doing this in a shorthand way, preferably an oneliner? I could, of course, just remove the newlines, but I rather mean something like the ? : thing for if.

谢谢.

推荐答案

您可以使用以下函数,然后使用该函数将try/catch单行.它的使用将受到限制,并使代码难以维护,因此我将永远不会使用它.

You could use the following function and then use that to oneline your try/catch. It's use would be limited and makes the code harder to maintain so i'll never use it.

var v = tc(MyTryFunc, MyCatchFunc);

tc(function() { alert('try'); }, function(e) { alert('catch'); });


/// try/catch 
function tc(tryFunc, catchFunc) {
     var val;
     try {
        val = tryFunc();
     }
     catch (e) {
         val = catchFunc(e);
     }
     return val;
} 

这篇关于尝试/抓住oneliner吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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