在JavaScript中返回虚假值,而不是true/fals



当函数应该返回true还是FALSE时,JavaScript中最佳实践是什么?我可以直接返回虚假的值而不是true还是错误?我找到了此代码:

function supportsAPL(handlerInput) {
  const supportedInterfaces = handlerInput.requestEnvelope.context.System.device.supportedInterfaces;
  const aplInterface = supportedInterfaces['Alexa.Presentation.APL'];
  return aplInterface != null && aplInterface !== undefined;
}

并将其简化为此代码:

function supportsAPL(handlerInput) {
   const {supportedInterfaces} = handlerInput.requestEnvelope.context.System.device;
   return supportedInterfaces['Alexa.Presentation.APL'];
}

哪个有效,但我不确定这是合适的/不错的JavaScript。我正在寻找经验丰富的JavaScript开发人员在找到第一个代码段(也希望保存代码行(之后会写的内容。

我认为'最佳实践'是始终返回呼叫者将使用它的内容。因此,在这种情况下,该函数被命名为 supportsapl ,它似乎应该返回是/否(true/false(,让呼叫者知道您提供的任何输入提供了函数是否支持APL。

您提到您简化了这一点:

return aplInterface != null && aplInterface !== undefined;

是:

return supportedInterfaces['Alexa.Presentation.APL'];

在这种情况下,我们从返回特定的true/false到返回supportedInterfaces['Alexa.Presentation.APL'];的值。如果支持APL,您将获得supportedInterfaces['Alexa.Presentation.APL'];的值,而如果不支持它,则可能会获得undefined

的虚假值

很有可能,呼叫者将做这样的事情:

if (supportsAPL(input)) {
    ...
}

const aplSupported = supportsAPL(input);
if (aplSupported) {
    ....
}

但是,如果您只返回真相,那么您将打破任何期待布尔返回的人。因此这些行不通:

if (supportsAPL(input) === true) {
    ...
}

const aplSupported = supportsAPL(input);
if (aplSupported === true) {
    ....
}

我认为,在这些情况下始终返回布尔值,因为这是功能的重点(确定输入是否支持APL(。

如@phil所述,

return aplInterface != null && aplInterface !== undefined;

可以简化以下:

return !!supportedInterfaces['Alexa.Presentation.APL']

最新更新