当函数应该返回 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/