gpt4 book ai didi

javascript - 属性和子属性未定义检查

转载 作者:行者123 更新时间:2023-12-02 21:32:22 25 4
gpt4 key购买 nike

我的代码中目前有这个 JavaScript 函数:

getCoverPhoto(item) {
if (item != undefined && item.gallery != undefined && item.gallery[0] != undefined)
return item.gallery[0].media;
return "";
}

如何简化if条件如上?如果不能简化,是否可以写得更好?

最佳答案

例如使用三元运算符:

getCoverPhoto(item) {
return item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';
}

进一步阅读documentation :

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

或者使用ES6+:

const getCoverPhoto = item => item && item.gallery && item.gallery[0] ? item.gallery[0].media : '';

希望对您有所帮助!

关于javascript - 属性和子属性未定义检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60589861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com