[英]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.