[英]How to return a boolean true if all the values in an array are true (strings) and if one of the value is false(string) stop checking using Javascript
[英]Checking for Boolean Values in Typescript/Javascript Pertaining to “true”, “false”, and “undefined”
我可以确保布尔检查的唯一结果是“ true”或“ false”的显式方法是什么? 换句话说,我想尽可能排除“ undefined”。 两种选择是:
功能一:
private canMove = (currentOptionSelected): boolean => {
if (this.client.services) {
for (const service of this.client.services) {
if (service === currentOptionSelected) {
if (service.currentStage === 'enrolling') {
return true;
}
}
}
}
}
功能二:
private canMove = (currentOptionSelected): boolean => {
if (this.client.services) {
for (const service of this.client.services) {
if (service === currentOptionSelected) {
return service.currentStage === 'enrolling';
}
}
}
}
编辑:在评论者的回应下,一个更可靠的选择是显式返回'false',如下所示:
private canMove = (currentOptionSelected): boolean => {
if (this.client.services) {
for (const service of this.client.services) {
if (service === currentOptionSelected) {
//You should also rethink this return statement
return service.currentStage === 'enrolling';
}
}
}
return false;
}
我将通过询问是否存在“ client.services”的情况添加一个额外的“ return'false'”来跟进,但是“ currentStage!=='enrolling”会更好吗? 还是在这种情况下第二个“ else”子句是多余的?
其次,他写道,我应该根据函数中的返回位置重新考虑return语句。 替代方案是什么? 简而言之,我正在尝试找到最健壮但简洁的方法来编写此函数。
这些不相等。 在第一个版本返回undefined
某些情况下,第二个版本返回false
。 调用者检查该值是否明确=== false
将观察到不同的行为。
两者都可以返回undefined
,这可能不是很大。 最好总是返回true
或false
的实际值
简短的回答是No ,它们不是等效的:
false
。 service.currentStage !== 'enrolling'
则第二个可以返回false
。 但是正如Ryan所述,两者都可以返回undefined
,您应该避免这种情况,只要不满足条件,就需要显式返回false
。
这应该是您的代码:
private canMove = (currentOptionSelected): boolean => {
if (this.client.services) {
for (const service of this.client.services) {
if (service === currentOptionSelected) {
//You should also rethink this return statement
return service.currentStage === 'enrolling';
}
}
}
return false;
}
注意:
return false;
当this.client.services
undefined
时,这里将确保您返回false
。 for
循环中使用return
语句是一个非常糟糕的主意,实际上您只会进行一次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.