javascript - 确认匹配的结束 boolean 问题 (JavaScript)

标签 javascript arrays string boolean

我正在尝试创建一个函数,如果字符串的结尾与给定变量相同,则返回该函数,而不使用 .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

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

最佳答案

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

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

关于javascript - 确认匹配的结束 boolean 问题 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49345837/

相关文章:

php - 执行通过 AJAX 加载的 Javascript

javascript - 当我在for中调用javascript函数时,当for循环结束时,返回该函数的所有第i个响应

ios - 将两个不同类型的数组排序为一个

java - 按轴表达式拆分 xpath 字符串

java - 将 K 互补数组对的效率提高到 O(NlogN)

javascript - 在 Chrome 中获取电池状态

javascript - 为什么我收到此错误 : Module build failed (from ./node_modules/babel-loader/lib/index.js) : Syntax Error Unexpected token, 预期 ","

javascript - PhoneGap——基本架构

c# - 函数不返回反转数组

php - 使用 LLVM API 将全局字符串存储在可变变量中