2017-11-09 11 views
0

私は練習問題のために以下のコードを持っています。誰かが正しい出力が元の場所で与えられていない理由を説明することができますか?Javascript/Elseが返答が正しくない場合

オリジナル回答:

function openSesame(array, str) { 
    for (var i in array) { 
    if (array[i] === str) { 
     return 'You may pass.'; 
    } else { 
     return 'You shall not pass!'; 
    } 
    } 
} 

正解:参考

function openSesame(array, str) { 
    for (var i in array) { 
    if (array[i] === str) { 
     return 'You may pass.'; 
    } 
    } 
    return 'You shall not pass!'; 
} 

var passwords = [ 
    'Password123', 
    'DavidYangsMiddleName', 
    'qwerty', 
    'S3cur3P455WORD', 
    'OpenSesame', 
    'ChildhoodPetsName', 
    'Gandalf4evaa' 
]; 

INPUT: openSesame(passwords, 'Password123'); 
OUTPUT: 'You may pass.' 
INPUT: openSesame(passwords, 'Balrog'); 
OUTPUT: 'You shall not pass!' 
+0

を見ない理由だことあなたの 'if/then'の値。これにより、 'for'ループは1回だけ実行されます。 –

答えて

0

elseを有する(現在の項目のいずれかに等しいすべての可能性が覆うので指定された文字列かそうでないか)を返します。つまり、ループを終了します最初の反復。

これは、配列の最初の項目が文字列と等しい場合にのみ関数が正解を返すことを意味します。他のすべての可能性については、"You shall not pass"を返します。

function openSesame(array, str) { 
 
    for (var i in array) { 
 
    // at this point, if array[i] is equal to str 
 
    // we will return "You may pass" 
 
    // if not, we will return "You shall not pass" 
 
    // Since this check happens on the first item 
 
    // and we return some result no matter what 
 
    // no other item will be reached 
 
    if (array[i] === str) { 
 
     return 'You may pass.'; 
 
    } else { 
 
     return 'You shall not pass!'; 
 
    } 
 
    } 
 
} 
 

 
var passwords = ['Password123', 'DavidYangsMiddleName', 'qwerty', 'S3cur3P455WORD', 'OpenSesame', 'ChildhoodPetsName', 'Gandalf4evaa']; 
 

 
passwords.forEach(pw => { 
 
    console.log(`openSesame(passwords, "${pw}") = "${openSesame(passwords, pw)}"`) 
 
})

+0

完璧です。ありがとうございました! – a12m12

+0

@ a12m12問題ありません、喜んで:) – nem035

0

あなたの最初のコードと同等です:

const i = Object.keys(array)[0]; 

if (array[i] === str) { 
    return 'You may pass.'; 
} else { 
    return 'You shall not pass!'; 
} 

それはあなたが `関わらずreturn`元で他の値

関連する問題