请教一下一个使我震惊的 js 语法 ?.(没错,看起来很像三目但却不是:而是.)

2020-04-16 14:29:18 +08:00
 devwolf
举例
let a = {a:"1",b:"2"}
console.log(a?.a)

契机:另一个组的同事在一个 angular 项目里发现了这个语法的使用,
通过关键字查了一下也就这么个 csdn 的结果
《 angular 中的 ? 和 !》 https://blog.csdn.net/weixin_30908941/article/details/95594290

里面除了交代?可以判断前面的变量是否为 null 或 undefined 再执行后面,还有个!判断后面键所对应的值是否为 null 或 undefined,不过没有成功在 js 里再现这个!。

就我个人在网上的搜索结果来看,感觉这个?.的写法比!!还要冷门,用途的效果上个人感觉类似 react 写 jsx 进行页面渲染时的&&或者?:

当然,我自己的这些肤浅猜测总结也没什么营养,还请各位有了解或者感兴趣的分析一波这个?.吗
15237 次点击
所在节点    Node.js
106 条回复
g00001
2020-04-16 15:05:01 +08:00
我觉得还是 aardio 中的直接下标更简洁好用,
if( a[[b]] ){ } 不管 a 是什么都不会抛异常,不是对象返回 null,可以节省好多代码。

比 swift,kotlin,js 什么的出现早多了,国产小语言也是有亮点的。
baozijun
2020-04-16 15:09:40 +08:00
Safe calls are useful in chains. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob's department head (if any), we write the following:

bob?.department?.head?.name
Such a chain returns null if any of the properties in it is null.
sarlanori
2020-04-16 15:15:10 +08:00
C#也有这个语法了
murmur
2020-04-16 15:16:53 +08:00
@luob 浏览器端不敢瞎 babel,比不了后端可以自己决定版本
xianxiaobo
2020-04-16 15:26:15 +08:00
有意思,学到了
yhxx
2020-04-16 15:28:33 +08:00
@liuy1994g 已经进 stage4 了
jadehare
2020-04-16 15:31:43 +08:00
ts 有插件会自动不上。。虽然我自己写还是 if 判断一下
zmqking
2020-04-16 15:35:08 +08:00
c# 里面也有!
9ki
2020-04-16 15:36:57 +08:00
要多想
Lax
2020-04-16 15:37:53 +08:00
为了减少对父元素的空置判定,尤其是很多个级别。
a.b.c.d 这种,if(a) { if(a.b) { if(a.b.c) { a.b.c.d }}}},不想一级一级判断的时候就很方便了。
goodboy95
2020-04-16 15:38:05 +08:00
握草,刚刚试了一下,除了?.运算符之外,??运算符也被支持了!
var a = {sa: 3, sb: 4};
var b = null;
console.log(a?.sa ?? 5); // 3
console.log(b?.sa ?? 5); // 5
yolee
2020-04-16 15:51:37 +08:00
c# 也是用这个判断是否为空的
lower
2020-04-16 15:53:45 +08:00
语法糖
Veneris
2020-04-16 15:55:28 +08:00
dart 也有
no1xsyzy
2020-04-16 15:55:38 +08:00
https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining
太超前了,FF 和 CR 各只过了两个版本,过 babel 可行( angular 可以用大概就是 babel 的原因?)
早前 coffee 就看到了
lithbitren
2020-04-16 15:55:49 +08:00
?? 和 || 有啥区别啊
liukangxu
2020-04-16 16:02:05 +08:00
看来 C#还是有人用的。。。
apeople
2020-04-16 16:05:42 +08:00
angular 也只是能在模板中使用吧,要想在 ts 中使用还是得配置 babel 插件。
DivineRapierH
2020-04-16 16:07:40 +08:00
@Lax #30 这种我一直是用 lodash 的 get 一把梭
Removable
2020-04-16 16:07:57 +08:00
C#里我经常这么用,比判断==null 方便多了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/663072

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX