javascript - 查看字符串结尾是否匹配

标签 javascript string

我有这个练习:检查字符串(第一个参数,str)是否以给定的目标字符串(第二个参数,target)结尾,而不使用方法endsWith()或任何其他方法。我的代码有什么问题吗?

function confirmEnding(str, target) {
  for (var i = 1; i <= target.length; i++) {
    val = false
    if (str[str.length - i] === target[target.length - i]) {
      val = true;
    }
    return val;
  }
}
confirmEnding("Bastian", "n");

//original code from post above:
console.log(confirmEnding("Bastian", "n")); //added to provide working example

最佳答案

您的原始代码存在一些问题:

将内联解决它们:

function confirmEnding(str, target) {
  // using a for loop to iterate over the target string's length
  for (var i = 1; i <= target.length; i++) {
    //setting up a variable that says false
    val = false
    //trying to compare the individual characters
    if (str[str.length - i] === target[target.length - i]) {
      //so what happens here:
      //when the two match this will set val to true
      //but every time the loop is run is will reset to false.
      val = true;
    }
    //the return value is in the loop, so the loop will run once
    return val;
  }
}
confirmEnding("Bastian", "n");

使用上面的脚本,您无法知道是否所有字符都匹配。如果最后一个字符匹配,它将返回 true,即使其他字符不匹配。

string: Bastian target: irr

将在循环逻辑中返回 true。

看看下面的代码和其中的注释!

function confirmEnding(str, target) {
  //get the length of the target string
  const targetLength = target.length;
  //set up an empty string  
  let endstr = "";
  for (let i = 1; i <= targetLength; i++)
  {
    //start at 1 since str.length-1 is last character
    //fill the empty string with the last characters of str
    endstr = str[str.length-i] + endstr;
  }
  //compare and return
  return target === endstr;
}

console.log(confirmEnding("Bastian", "ian")); //TRUE
console.log(confirmEnding("Bastian", "in")); //FALSE

关于javascript - 查看字符串结尾是否匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59698985/

相关文章:

c++ - C++中字符串的堆内存

javascript - 从 JSON 响应中的键名称中删除句点

javascript - 如何在服务器上查找 MongoDB 数据。 Docker部署的代码?

java - 在 Java 中搜索集合

javascript - Atom 无法为数组中的字符串元素着色

java - 在 Java 中将二维整数数组转换为字符和字符串

java - 从字符串中删除字符

javascript - 删除重复的数组元素

javascript - React 钩子(Hook)真的必须以 "use"开头吗?

javascript - 我们如何使用 Regex 验证 CSR 的格式