首页 > 解决方案 > Dart 等价于带有潜在 null 值的 JavaScript &&

问题描述

有一个常见的 JavaScript 习惯用法(也用于少数其他语言)在某些内容为空时使用替代值。

return theValue || "don't know";

Dart 有一个类型安全的替代方案,它不依赖于隐式真/假转换,并且在 80% 到 90% 的情况下做同样的事情:

return theValue ?? "don't know";

或类似的 JavaScript:

myValue = myValue || "don't know";

在飞镖中:

myValue ??= "don't know";

JavaScript 也有一个类似的习惯用法,用于有条件地做一些具有潜在null价值的事情:

return theValue && theValue.shoeSize;

Dart 的类型安全替代方案:

return theValue?.shoeSize

但是有一个非常常见的情况在 Dart 中没有涵盖:

return theValue && getShoeSize(theValue);

在飞镖中:

return theValue == null ? null : getShoeSize(theValue);

想一想,如果 Dart 有这样一个运算符,它可能会变成这样:

return theValue ?& getShoeSize(theValue);

或类似的东西。由于文档中没有任何类似的东西出现,我认为带有显式的标准三元? null :是 Dart 程序员做的最好的事情?

标签: dart

解决方案


推荐阅读