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