JavaScript中的可选链接 [英] Optional Chaining in JavaScript

查看:142
本文介绍了JavaScript中的可选链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在Swift编程了很多。今天我在JavaScipt中做了一些工作,当问题出现在我身上时:

I've been programming a lot in Swift recently. Today I did some work in JavaScipt when question popped up to me:

在JavaScript中有类似于可选链接的东西吗?一种防止 undefined的方法不是一个没有任何变量的对象

Is there something similar to optional chaining in JavaScript? A way to prevent undefined is not an object without any variables?

示例:

function test(){
   if(new Date() % 2){
      return {value: function(){/*code*/}};
   }
} 

test().value();

将失败一半时间,因为有时 test 返回undefined。

will fail half of time because sometimes test returns undefined.

我能想到的唯一解决方案是功能:

The only solution I can think of is a function:

function oc(object, key){
   if(object){
      return object[key]();
   }
}

oc(test(), 'value');

我希望能够做到这样的事情:

I would like to be able to do something like:

test()?.value()

只有在 test 返回一个对象时,才会执行问号后的部分。

The part after the question mark is only executed if test returned an object.

但这不是很强大。还有更好的东西吗?运营商的神奇组合?

But this is not very elegeant. Is there something better? A magic combination of operators?

编辑我知道我可以重写 test 来返回一些内容。但我想知道是否有类似可选链接的东西。我对上面示例的特定解决方案不感兴趣。如果无法控制函数返回undefined,我也可以使用。

Edit I know I could rewrite test to return something. But I'm wondering if there's something like optional chaining. I'm not interested in a particular solution to the above example. Something that I also can use if have no control over the function returning undefined.

推荐答案

在纯JavaScript中你必须进行类型检查或者构造你的代码,以便你知道一个对象将存在。

In plain JavaScript you have to do type checks or structure your code so that you know an object will exist.

CoffeeScript是一种编译成JavaScript的语言,它提供了一个存在运算符?。 如果您愿意考虑预处理语言,请进行安全链接。

CoffeeScript, a language that compiles down to JavaScript, provides an existential operator ?. for safe chaining if you're willing to consider a preprocessed language.

还有另一个讨论这里关于为什么你不能在JS中重现这种行为。

There's another discussion here about why you can't reproduce this behavior in JS.

在ESDiscuss论坛上还有讨论关于在未来版本的JavaScript中添加存在运算符。虽然它似乎并不遥远,但实际上并没有接近实际用途。此时更多的想法。

There is also a discussion on the ESDiscuss forums about adding an existential operator to a future version of JavaScript. It doesn't seem very far along though, certainly nowhere close to practical use. More of an idea at this point.

这篇关于JavaScript中的可选链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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