javascript - 在 javascript 中返回假值而不是 true/false

标签 javascript ecmascript-6

当函数应该返回 true 或 false 时,JavaScript 中的最佳实践是什么?我可以直接返回假值而不是 true 或 false 吗? 我找到了这段代码:

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']; 的值,而如果不支持,您可能会获得 的虚假值未定义

调用者很可能会做这样的事情:

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

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

但是,如果您只返回 true falsy,那么您将会破坏任何期望 bool 值返回的人。所以这些行不通:

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

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

在我看来,在这些场景中始终返回一个 bool 值,因为这是函数的要点(确定输入的内容是否支持 APL)。

正如@Phil 提到的,

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

可以简化为:

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

关于javascript - 在 javascript 中返回假值而不是 true/false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57367252/

相关文章:

javascript - 使用 lodash 将相同的键转换为一个键并创建它的值数组

javascript - 调用函数数组,每个函数接收一个回调

javascript - 如何使用相同的组件值映射 2 个不同的数组?

javascript - 如何从对象中提取2字字段?

javascript - 如何使用错误子状态在 Ember.js 中显示整页错误?

javascript - ChartJS 在图例中显示值 (Chart.js V3.5)

javascript - Jquery 和 Bootstrap

javascript - Node.js - 标准库

javascript - ES6 promise ,仅当先前的 promise 被拒绝时才链接 promise ,同时保留拒绝原因

mvvm - Vue2 : How to specify the vue-router root component?