简体   繁体   English

为什么即使不满足条件,用JS编写的Function也会返回true?

[英]Why does this Function written in JS return true even if the condition is not satisfied?

I am just starting to learn Javascript and one of our first assignments were the classic check_if_palindrome function. 我才刚刚开始学习Javascript,而我们的第一个任务就是经典的check_if_palindrome函数。 I don't understand what is wrong with my code. 我不明白我的代码有什么问题。

 function palindrome(str1) { console.log(str1.split('').reverse().join('')); console.log(str1); if (str1 == str1.split().reverse().join('')) { return (true) } else { return (false) } } if (palindrome('wow442421') == true) { console.log('YES') } else { console.log('NOPE'); } 

You are missing the '' in the second split() . 您在第二个split()中缺少了'' Do not repeat code, it is error prone, you should use a variable to hold the result and reuse it when necessary: 不要重复代码,因为它容易出错,您应该使用变量保存结果,并在必要时重新使用它:

 function palindrome(str1) { const reversed = str1.split('').reverse().join(''); console.log(str1, reversed); if (str1 === reversed){ return true } else { return false } } if (palindrome('wow442421') === true) { console.log('YES') } else{ console.log('NOPE'); } 

Also, since str1 === str1.split('').reverse().join('') already returns a boolean, simply return this value, the if/else statement is not necessary: 另外,由于str1 === str1.split('').reverse().join('')已返回布尔值,因此只需返回此值,就不需要if/else语句:

 function palindrome(str) { return str.split('').reverse().join('') === str; } if (palindrome('wow442421')) { console.log('YES') } else{ console.log('NOPE'); } 

And if you want to make it more succinct, you can do this: 如果要使其更简洁,可以执行以下操作:

 const isPalindrome = str => str === [...str].reverse().join('') console.log(isPalindrome('wow44')); console.log(isPalindrome('Roma amoR')); 

You should use split('') instead of split() , split() will split at every space character, split('') splits at every character, which is what you want: 您应该使用split('')而不是split()split()将在每个空格字符处split('')split('')在每个字符处分割,这就是您想要的:

 function palindrome(str1) { if (str1 == str1.split('').reverse().join('')) { return true; } else { return false; } } if (palindrome('wow442421') == true) { console.log('YES') } else { console.log('NOPE'); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM