Shorthand 为:如果不为假则赋值 javascript

Shorthand for: assign if not false javascript

想看看 shorthand 我经常做的事情是否存在。

我通常 write/use 函数如果不能做他们能做的事,就会 return false,但如果可以,就会是一个对象。 我也可能经常想检查是否成功。

例如

function someFunc() {
    // assume a is some object containing objects with or without key b
    // edit: and that a[b] is not going to *want* to be false
    function getAB(a, b) {
        if(a[b]) return a[b];
        return false;
    }

    let ab = getAB(a, b);
    if(!ab) return false;
}

我只是想知道是否有某种 shorthand 用于此。 例如,在幻想世界中,

//...
let ab = getAB(a, b) || return false
//...

您可以使用 or 运算符,例如:

return a[b] || false

您的完整示例代码可以写成:

function someFunc() {
    // assume a is some object containing objects with or without key b
    function getAB(a, b) {
      return a[b] || false
    }

    return getAB(a, b); // getAB already returns the value, no need to check again.
}