有没有一种优雅而简洁的方法来避免在javascript中检查深入对象成员层次结构的值?
handlerInput.supportsDisplay = function() {
return this.requestEnvelope.context &&
this.requestEnvelope.context.System &&
this.requestEnvelope.context.System.device &&
this.requestEnvelope.context.System.device.supportedInterfaces &&
this.requestEnvelope.context.System.device.supportedInterfaces.Display;
}
发布于 2018-08-27 01:32:09
除非你使用助手函数或第三方库,否则在普通的JavaScript中目前还没有简洁的方法来做到这一点。
有一个proposal (截至2018年8月的第1阶段)可以将?.
运算符添加到JavaScript中,它可以执行您想要的操作。
接受了该建议后,您将能够在任何可能缺少属性的地方使用?.
而不是.
,因此您的代码将变为:
// careful: this syntax is not available yet
var hasDisplay = handlerInput.requestEnvelope.context?.System?.device?.supportedInterfaces?.Display
发布于 2018-08-27 01:32:00
我写了一个NPM模块,它允许你通过字符串路径进行查询。
https://www.npmjs.com/package/js-path-resolver
http://www.twelvetone.tv/docs/developer-tools/npm-modules/js-path-resolver
这是一个codepen https://codepen.io/Flamenco/pen/xaVKjR/?editors=1111
对于您的用例:
import resolver from 'js-path-resolver'
const info = resolver(handlerInput, 'requestEnvelope.context.System.device.supportedInterface.Display', {onError:'continue'})
const hasDisplay = info.exists
const display = info.get()
简而言之,您拆分字符串,然后尝试解析路径,一次解析一个字符串。实现这一点有各种各样的问题,比如转义点、处理数组索引等,所以使用库可以让工作变得容易得多。在此库中,还可以设置和删除已解析的路径。
https://stackoverflow.com/questions/52028640
复制相似问题