测试两个序列的起始字符彼此相对

时间:2013-07-24 01:23:27

标签: javascript

我正在通过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"));

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

你几乎拥有它,但你还必须通过sentenceOnesentenceTwo通过参数(我们称之为firstSentencesecondSentence)来传递给你的函数,它可以与他们合作。否则,该信息超出了函数的范围!

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);