javascript - 如何将布尔值作为表达式返回以替换 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"));
解决方案
只需返回评估表达式的布尔值
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"));
推荐阅读
- c# - 在一次调用中接收按文档类型分组的搜索结果(NEST、AWS Elasticsearch)
- c# - 网格中的网格不显示 C# WPF 中的滚动条
- vba - VBA 中的嵌套循环和条件问题
- java - DriveClient 需要使用哪些库?
- rose-compiler-framework - EDG 二进制压缩包不可用
- javascript - 在数据表中提取和显示附加数据
- jq - 如何在jq中递归地做模糊搜索键名
- angular - FabricJs - 大图像移动滞后
- google-apps-script - 访问表单 ID 时抛出“不允许操作”异常
- symfony - 使用 rsync 命令将项目部署到远程服务器