基本算法脚本:确认结局
检查字符串(第一个参数,str)是否以给定的目标字符串(第二个参数,target)结尾。

可以使用ES2015中引入的.endsWith()方法解决此挑战。但是出于此挑战的目的,我们希望您改用一种JavaScript子字符串方法。

confirmEnding(“ Bastian”,“ n”)应该返回true。
已通过
confirmEnding(“ Congratulation”,“ on”)应该返回true。
已通过
confirmEnding(“ Connor”,“ n”)应该返回false。
ConfirmEnding(“如果冻结,则从规范中进行开发和开发软件很容易”,“ specification”)应返回false。
已通过
validateEnding(“他必须给我一个新名字”,“名字”)应该返回true。
已通过
confirmEnding(“ Open sesame”,“ same”)应该返回true。
已通过
ConfirmEnding(“芝麻开”,“笔”)应返回false。
confirmEnding(“ Open sesame”,“ game”)应该返回false。
已通过
confirmEnding(“如果您想拯救我们的世界,您必须快点。我们不知道我们可以承受多长时间。”,“ mountain”)应该返回false。
已通过
confirmEnding(“ Abstraction”,“ action”)应该返回true。

我无法使用当前代码传递第4和第8种情况。

function confirmEnding(str, target)
{
  // "Never give up and good luck will find you."
  // -- Falcor
  var first = str.length;
  let last  = target.length;
  for (var i = first-1; i>last-1; i--)
  {
    if(str[i]===target[last-1])
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}

confirmEnding("Bastian", "n");

最佳答案

只是很有趣



const Vals=
[ { r:'Bastian',        t:'n' }
, { r:'Congratulation', t:'on' }
, { r:'Connor',         t:'n' }
, { r:'Walking on water and developing software from a specification are easy if both are frozen', t:'specification' }
, { r:'He has to give me a new name', t:'name' }
, { r:'Open sesame', t:'same' }
, { r:'Open sesame', t:'pen' }
, { r:'Open sesame', t:'game' }
, { r:'If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing', t:'mountain' }
, { r:'Abstraction', t:'action' }
]


function confirmEnding(strRef, target)
{
  let t = target.length
    , r = strRef.length
  while ( r>=0
       && t>=0
       && target.charAt(--t)==strRef.charAt(--r)
       ) {}
  return (t<0)
}


for (let test of Vals)
{
  console.log ( confirmEnding(test.r , test.t), ':', test.r , '==>' , test.t)
}

09-25 15:46