简体   繁体   English

如何将 Boolean 作为表达式返回以替换 if、else true 和 false

[英]How to return a Boolean as an expressiont to replace if, else true and false

I am trying to solve a challenge in freecodecamp and I dont want to write twice return true and false.我正在尝试解决 freecodecamp 中的一个挑战,我不想写两次返回 true 和 false。 Instead I am looking for minimizing code and write an expression that evaluates to a boolean相反,我正在寻找最小化代码并编写一个计算结果为 boolean 的表达式

function confirmEnding(str, target) {

    if(str.substr(-target.length) === target){

        //Code that evaluates and returns and expression as a boolean 

    }

}

console.log(confirmEnding("Connor" , "n"));

Simply return the boolean value of evaluating the expression只需返回计算表达式的 boolean 值

 function confirmEnding(str, target) { return str.substr(-target.length) === target; } console.log(confirmEnding("hello", "lo")); console.log(confirmEnding("loollo", "lo")); console.log(confirmEnding("leo", "lo"));

Here is another way这是另一种方式

 function confirmEnding(str, target) { return str.lastIndexOf(target) + target.length === str.length; } console.log(confirmEnding("hello", "lo")); console.log(confirmEnding("loollo", "lo")); console.log(confirmEnding("leo", "lo"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将var t =!0 / var t =!1用作true / false有多安全? 他们是否总是返回true布尔值true / false? - How safe is using var t=!0 / var t=!1 for true / false? Do they always return true boolean true / false? 如何使用布尔值查询 MongoDB 中的字段并返回一个布尔值是真还是假 - How to query a field in MongoDB with a boolean value and return a boolean whether it's true or false 在JavaScript函数中返回布尔值true或false - Return boolean true or false in a JavaScript function 带有布尔返回的jQuery UI对话框 - true或false - jQuery UI dialog with boolean return - true or false 如果前一个字符串为真,则返回假,否则为真 - javascript - If previous string was true, return false, else true - javascript 如何将布尔值true / false或字符串'true'/'false'列入白名单 - How to whitelist boolean true/false or string 'true'/'false' 如何将布尔值true / false更改为字符串 - How to change Boolean true/false into strings 如何在javascript中将布尔值true或false转换为1或0 - How to convert boolean true or false into 1 Or 0 in javascript 如何在javascript中为未知类型变量的值返回布尔值true / false? - How to return boolean true/false in javascript for an unknown type variable's value? 如果字符串中的所有字符都是“x”或“X”,则返回“True”,否则返回 false - Return "True" if all the characters in a string are "x" or "X" else return false
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM