本文来自个人博客,欢迎你们去GitHub上star个人博客node
咱们在取值特别是链式取值的时候,经常会遇到Cannot read property 'xx' of undefined
的错误,如何避免这种状况的发生呢?这里有几种方法以供参考git
这是最简单的一种手段:只用引入lodash,使用_.get
方法;或者引入Ramda,使用R.path
方法,咱们就能规避出现上述错误的风险es6
尽管这种方法十分奏效且方便,但我仍是但愿你能看完其余方法github
咱们知道,在JavaScript中,使用&&或者||操做符,最后返回的值不必定是boolean类型的,好比下面这个例子:数组
console.log(undefined && "a"); //undefined console.log("a" && "b"); //b console.log(undefined || "a"); //a console.log("a" || "b"); //a
&&:若是第一项是falsy(虚值,Boolean上下文中已认定可转换为‘假‘的值),则返回第一项,不然返回第二项浏览器
||:若是第一项是falsy,返回第二项,不然返回第一项安全
咱们能够利用这种规则进行取值babel
咱们先拟一个数据app
const artcle = { authorInfo: { author: "Bowen" }, artcleInfo: { title: "title", timeInfo: { publishTime: "today" } } };
接下来利用&&和||进行安全取值:函数
console.log(artcle.authorInfo && artcle.authorInfo.author); //Bowen console.log(artcle.timeInfo && artcle.timeInfo.publishTime); //undefined console.log(artcle.artcleInfo && artcle.artcleInfo.timeInfo && artcle.artcleInfo.timeInfo.publishTime ); //today console.log((artcle.authorInfo || {}).author); //Bowen console.log((artcle.timeInfo || {}).publishTime); //undefined console.log(((artcle.artcleInfo || {}).timeInfo || {}).publishTime); //today
不难看出,这两种方法都不算优雅,只适用短链式取值,一旦嵌套过深,使用&&须要写一长段代码,而使用||须要嵌套不少括号
咱们能够利用es6的解构赋值,给属性一个默认值,避免出现错误。以上文的artcle数据为例,以下:
const { authorInfo: { author } = {} } = artcle; console.log(author); //Bowen
上面这么作会暴露不少变量出来,咱们能够简单地封装一个函数,以下:
const getAuthor = ({ authorInfo: { author } = {} } = {}) => author; console.log(getAuthor(artcle)); //Bowen
这样作不会将变量暴露出来,同时getAuthor函数也能复用,优雅多了
既然在取值的过程当中会出现错误,那咱们天然能够利用try catch
提早将错误捕获:
let author, publishTime; try { author = artcle.authorInfo.author; } catch (error) { author = null; } try { publishTime = artcle.timeInfo.publishTime; } catch (error) { publishTime = null; } console.log(author); //Bowen console.log(publishTime); //null
这个方法很差的地方在于:咱们没法在一个try catch语句里进行屡次取值,由于只要有任一错误,就会进入catch语句中去
咱们能够写一个通用函数优化这一流程:
const getValue = (fn, defaultVaule) => { try { return fn(); } catch (error) { return defaultVaule; } }; const author = getValue(() => artcle.authorInfo.author); const publishTime = getValue(() => artcle.timeInfo.publishTime); console.log(author); //Bowen console.log(publishTime); //undefined
这是我在网上看到的一个十分有意思的写法,利用了es6中的proxy完成的:
const pointer = function(obj, path = []) { return new Proxy(function() {}, { get: function(target, key) { return pointer(obj, path.concat(key)); }, apply: function(target, object, args) { let value = obj; for (let i = 0; i < path.length; i++) { if (value == null) { break; } value = value[path[i]]; } if (value === undefined) { value = args[0]; } return value; } }); }; const proxyArtcle = pointer(artcle); console.log(proxyArtcle.authorInfo.author()); //Bowen console.log(proxyArtcle.publishTime()); //undefined
原理比较简单,咱们能够看到,pointer方法返回的是一个以空函数为代理对象的Proxy实例,而在每次取值的时候会将key保存下来,以proxyArtcle.authorInfo.author
为例,它其实等价于pointer(artcle, ["authorInfo", "author"])
。因为是以空函数为代理对象,咱们能够将执行它,触发apply。apply中会遍历path数组依次取值,若是发现没法继续取值则break,跳出循环。
若是你尚未学习proxy,能够花几分钟了解一下:proxy
这种方法在我看来已经是比较优雅的解决方法,但因为proxy对浏览器和node版本有所限制,且不可能有polyfill,真正应用起来须要考虑太多
这是一个新特性,尚在提案阶段,具体能够看tc39/proposal-optional-chaining,不过已经有babel可使用了:babel-plugin-proposal-optional-chaining
咱们能够像下面同样使用这个特性:
console.log(artcle?.authorInfo?.author); //Bowen console.log(artcle?.timeInfo?.publishTime) //undefined
这种方法已接近完美,咱们能够期待它的真正落实