首页 > 解决方案 > 简写:如果不是 false 则分配 javascript

问题描述

看看我所做的事情的速记是否普遍存在。

我通常编写/使用函数,如果不能做他们能够做的事情,它们将返回 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;
}

我只是想知道是否有某种速记。例如,在幻想世界中,

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

标签: javascriptjavascript-objectsshorthand

解决方案


您可以使用 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.
}

推荐阅读