繁体   English   中英

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

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

我正在尝试解决 freecodecamp 中的一个挑战,我不想写两次返回 true 和 false。 相反,我正在寻找最小化代码并编写一个计算结果为 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"));

只需返回计算表达式的 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"));

这是另一种方式

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM