Shorthand for: assign if not 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
//...

您可以使用或运算符,如:

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.
}

最新更新