我有这个练习:检查字符串(第一个参数,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/