2016-07-31 66 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"]) 
 
)

相关问题