2013-07-24 112 views
0

兩個句子的測試開始字符,我通過機鋒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")); 
+0

(sentenceOne.slice(0,chars.length)== chars)&&(sentenceTwo.slice(0,chars.length)== chars); – gezzuzz

+0

它可能工作,但更清晰的方法是:'return sentenceOne.slice(0,chars.length)=== chars && sentenceTwo.slice(0,chars.length)=== chars;' –

回答

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/

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