2016-07-31 64 views
-1

爲什麼我的解決方案不適合這項挑戰? (鏈接挑戰:https://www.freecodecamp.com/challenges/mutationsFreeCodeCamp Javascript挑戰[突變]我的解決方案有什麼問題?

function mutation(arr) { 
    var first = arr[0].toLowerCase(); 
    var second = arr[1].toLowerCase(); 
    for (var i = 0; i < first.length; i++) { 
    if (first.indexOf(second[i]) === -1) { 
     return false; 
    } else { 
     return true; 
    } 
    } 
} 

mutation(["hello", "hey"]); 
+1

你不會讓我谷歌,是嗎?什麼是挑戰,你的代碼的預期行爲是什麼,它的實際行爲是什麼? –

+0

你是否正在調用函數並利用返回值? – xCodeZone

+0

是的。調用:突變([「hello」,「hey」]); – veron

回答

0

不需要循環,因爲你的數組大小爲2反正:

function mutation(arr) { 
 

 

 
    return arr[1].toLowerCase().split('').map((ch)=>arr[0].toLowerCase().indexOf(ch)>=0).every((e)=>e) 
 
} 
 

 
console.log(
 
    mutation(["hello","Hello"]) 
 
) 
 
console.log(
 
    mutation(["Alien", "line"]) 
 
) 
 
console.log(
 
    mutation(["hello","hey"]) 
 
)

解釋代碼mutation(["Alien", "line"])爲例:

  • arr[1].toLowerCase().split('') =>分裂line到陣列['l','i','n','e']

  • ['l','i','n','e'].map((ch)=>arr[0].toLowerCase().indexOf(ch)>=0)對於每個字符,檢查它是否存在於第一elememt arr[0] ==>其結果將是[true,true,true,true]

  • 應用和邏輯運算符中那結果[true,true,true,true].every((e)=>e) ==>true & true & true & true

  • 結果爲true

+0

這裏你需要'.every',而不是'reduce'。 – georg

+0

我更新了答案,我解釋我的解決方案..這是機會學習:) –

+0

@georg:謝謝你的提醒..更新! '。每((E)=> E)' –

0

您這裏需要While環比for循環:

function mutation(arr) { 
 
    var j=0,first = arr[0].toLowerCase(),second = arr[1].toLowerCase(); 
 
    
 
    while(j<second.length && first.indexOf(second[j])>=0){ 
 
      j++; 
 
    } 
 
    return !(j===second.length-1) 
 
    
 
} 
 
    //-------- SAMPLES 
 
console.log(
 
    mutation(["hello", "Hello"]) 
 
) 
 

 
console.log(
 
    mutation(["hello", "hey"]) 
 
) 
 

 
console.log(
 
    mutation(["Alien", "line"]) 
 
)

相關問題