0

我正在通过 Eloquent JavaScript 工作并遇到了这种做法:

编写一个名为startsWith 的函数,它接受两个参数,都是字符串。当第一个参数以第二个参数中的字符开头时,它返回 true,否则返回 false。

这是他们给出的答案:

function startsWith(string, pattern) {
return string.slice(0, pattern.length) == pattern;
}

show(startsWith("rotation", "rot"));

但我想要一个更彻底的程序,它会获取开始字符chars并在每个句子中测试它们,并吐出每个句子中的开始字符是否相同。我是 JavaScript 和编程的新手,所以任何帮助将不胜感激!这是我认为可行的方法:

var sentenceOne = "Pretty kitty doesn't like you!";
var sentenceTwo = "Preachy cat loves you.";
function startsWith(chars) {
  return (sentenceOne.slice(0, chars.length) == chars) == (sentenceTwo.slice(0, chars.length) == chars);
}
show(startsWith("pre"));
4

2 回答 2

0

给出的答案非常彻底。给定两句话,你可以简单地做:

var sentenceOne = "Pretty kitty doesn't like you!";
var sentenceTwo = "Preachy cat loves you.";

show(startsWith(sentenceOne, "Pre") === startsWith(sentenceTwo, "Pre"));

您不需要一个全新的函数来简单地检查两个字符串是否以相同的模式开头。查看演示:http: //jsfiddle.net/p3unn/1/


另一种方法是,给定两个句子和一个模式,您可以测试起始字符是否相同:

function startWith(sentenceOne, sentenceTwo, pattern) {
    return !(sentenceOne.indexOf(pattern) || sentenceTwo.indexOf(pattern));
}

现在您只需执行以下操作:

show(startWith(sentenceOne, sentenceTwo, "Pre"));

查看演示:http: //jsfiddle.net/p3unn/2/

于 2013-07-24T01:41:56.687 回答
0

您几乎已经完成了,但您还必须将sentenceOneandsentenceTwo参数(让我们称之为firstSentenceand secondSentence)传递给您的函数,以便它可以使用它们。否则,该信息超出了该功能的范围!

var sentenceOne = "Pretty kitty doesn't like you!";
var sentenceTwo = "Preachy cat loves you.";
function startsWith(chars, firstSentence, sencondSentence) {
  return (sentenceOne.slice(0, chars.length) == chars) == (sentenceTwo.slice(0, chars.length) == chars);
}
show(startsWith("pre"), sentenceOne, sentenceTwo);
于 2013-07-24T01:56:17.740 回答