【问题标题】:How to return a Boolean as an expressiont to replace if, else true and false如何将布尔值作为表达式返回以替换 if、else true 和 false
【发布时间】:2020-05-27 13:41:25
【问题描述】:

我正在尝试解决 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"));

【问题讨论】:

  • 欢迎来到 SO。您能否举一个替换注释的代码示例?
  • 我还没有解决。是这个吗:freecodecamp.org/learn/…

标签: javascript arrays string


【解决方案1】:

简单地返回计算表达式的布尔值

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

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 2016-03-18
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2020-06-23
    相关资源
    最近更新 更多