function confirmEnding(str, target) {
var end = target;
var match = '';
for(var x = 0; x < str.length; x++){
for(var j = 0; j < str[x].length; j++){
if(str[x][j]){
match = str[x][j];
}
}
}
return match.substr(-target.length) === target;
}
confirmEnding("He has to give me a new name", "name");
但我想知道我是否可以遍历字符串,然后使用适当的索引检查它。
有人可以理解我的方法并让我知道它如何/为什么不可行吗?
它目前只检查最后一个字符,所以整个单词都不起作用。我知道下面的行会起作用
return str.substr(-target.length) === target;
会起作用,但有人可以帮助我采用我的方法吗
编辑:
我稍微改变了一点,接近了但仍然没有运气。
function confirmEnding(str, target) {
for(var x = str.length-1; x < str.length; x++){
for(var j = target.length-1; j>=0; j--){
if(str[x] === target[j]){
return true;
} else{
return false;
}
}
}
}
confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification");
当它应该返回 false 时,它返回 true。我明白为什么,但想到了一个决心。
如果使用循环是一个严格的要求,那么我会以某种方式做到这一点
function confirmEnding(source, target) {
var lengthT = target.length;
var lengthS = source.length;
for(var x = 0; x < lengthT; x++) {
if(source[lengthS - 1 - x] !== target[lengthT - 1 - x]) {
return false;
}
}
return true;
}
confirmEnding("He has to give me a new name", "name"); // true
但是confirmEnding
方法的更简单的实现只是
function confirmEnding(source, target) {
return source.substr(source.length - target.length, target.length) === target;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句