首页 > 解决方案 > 如何将布尔值作为表达式返回以替换 if、else true 和 false

问题描述

我正在尝试解决 freecodecamp 中的一个挑战,我不想写两次返回 true 和 false。相反,我正在寻找最小化代码并编写一个计算为布尔值的表达式

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"));

标签: javascriptarraysstring

解决方案


只需返回评估表达式的布尔值

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"));


推荐阅读