【问题标题】:Confirming a Matching Ending Boolean Issue (JavaScript)确认匹配的结束布尔问题 (JavaScript)
【发布时间】:2018-03-18 08:17:22
【问题描述】:

我正在尝试创建一个函数,如果字符串的结尾与给定变量相同,则返回该函数,而不使用 .endsWith()。

我不确定为什么这不起作用。链接 .join("") 并将两个值作为字符串进行比较,但不能作为数组。

const confirmEnding = (str, target) => {
// split string into array, splice end of array based on target length
console.log(str.split("").splice(str.length - target.length, target.length));
// split target into array
console.log(target.split(""));
// compare two arrays
return str.split("").splice(str.length - target.length, target.length) === target.split("");

console.log(confirmEnding("Congratulation", "on"));

输出

[ 'o', 'n' ]
[ 'o', 'n' ]
false

显然,数组是完全相同的。为什么布尔值返回 false?

【问题讨论】:

  • 您不能比较两个具有相同内容但具有不同对象引用的数组。您需要比较项目。
  • 您应该阅读这个问题stackoverflow.com/questions/7837456/… 及其答案
  • 知道了,我不知道数组不能像原始数据类型那样进行比较。
  • 一点帮助:a = [1,2,3]; b = [1,2,3]; console.log(a === a); /* true */ console.log(a === b); /* false */ :-)

标签: javascript arrays string boolean


【解决方案1】:

您不能比较具有相同内容但具有不同对象引用的两个数组。您需要使用计数器来比较项目,从字符串的末尾开始迭代相等的字符。

const confirmEnding = (str, target) => {
  var i = 0;
  while (i < target.length && str[str.length - 1 - i] === target[target.length - 1 - i]) {
      i++;
  }
  return i === target.length;
}

console.log(confirmEnding("Congratulation", "on"));
console.log(confirmEnding("Congratulation", "off"));

【讨论】:

    【解决方案2】:

    您可以更改逻辑以使其变得简单。只需从str 中获取lastIndexOftarget 字符串,以便您可以获取最后一个单词的子字符串并将其与target 进行比较:

    const confirmEnding = (str, target) => {
      var indexOfTarget = str.lastIndexOf(target);
      var lastStr = str.substr(indexOfTarget, str.length - 1);
      if(lastStr === target){
        return true;
      }
      return false;
    };
    //match
    console.log(confirmEnding("Congratulation", "on"));
    //match
    console.log(confirmEnding("Congratulation", "tion"));
    //no match
    console.log(confirmEnding("Congratulation", "ons"));

    【讨论】:

    • 你没有回答这个问题:“为什么布尔值返回 false?”。
    • @leaf 我理解您的评论,但我更愿意建议一个更好的答案,尽管给出的答案的原因并不适合实现 OP 想要实现的目标。
    • 那么your logic 不连贯:-P
    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2022-01-21
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多