我有这个练习:不使用方法endsWith()
或任何其他方法,检查字符串(第一个参数,str)是否以给定的目标字符串(第二个参数,目标)结尾。我的代码有什么问题?
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
答案 0 :(得分:1)
在您的原始代码中,存在一些问题:
将内联处理它们:
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
答案 1 :(得分:0)
当前代码中的问题是结果变量在循环内被初始化。
因此,实际上它仅根据比较的最后一个字符返回true / false。
这将是目标字符串的第一个字符。
您所能做的就是一旦发现差异就退出该循环。
另外,还要检查字符串是否不小于目标字符串,因为这样无论如何它都是假的。
F.e。
function confirmEnding(str, target) {
if(str.length < target.length)
return false;
for (var i = 1; i <= target.length; i++) {
if (str[str.length - i] !== target[target.length - i]) {
return false;
}
}
return true;
}
console.log(confirmEnding("Bastian", "ian"));
console.log(confirmEnding("Bastian", "ion"));
console.log(confirmEnding("an", "ian"));