Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

lodash 的get用法是什么样的啊?

image.png

类似这种,是什么用法呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

安全取值,防止因为 undefined/null 等原因抛出异常,最后一个参数表示如果不存在对应路径得属性时返回的默认值。

正常写的话就是:

return this.$route.meta.pChild.Create || false;

metameta.pChildmeta.pChild.Create 每一级都有可能不存在导致抛出异常,所以健壮性稍微好一点儿的话就得写成:

return this.$route && this.$route.meta && this.$route.meta.pChild && this.$route.meta.pChild.Create || false;

但其实这种利用布尔短路的写法是有弊端的,最健壮的写法其实是:

// 用嵌套 if 理解起来更容易,你要简写成一坨三元表达式也不是不行
if (this.$route !== undefined && this.$route !== null) {
    if (this.$route.meta !== undefined && this.$route.meta !== null) {
        if (this.$route.meta.pChild !== undefined && this.$route.meta.pChild !== null) {
            if (this.$route.meta.pChild.Create !== undefined && this.$route.meta.pChild.Create !== null) {
                return this.$route.meta.pChild.Create;
            }
        }
    }
}

return false;

但这写起来多恶心?lodash 就封装了一下。

P.S. ES2020 / TS 中可以已经可以利用可选链双问号操作符这两个新语法优雅地处理了:

return this.$route?.meta?.pChild?.Create ?? false;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...