Answered by:
Why is this code always false?

Question
-
User-2049827838 posted
<!DOCTYPE html> <html lang="en"> <head> <title>test</title> </head> <body> <p id="answer"></p> <input type="text" id="Power" /> <button type="button"onclick="test()">test</button> <script> function test() { var strength = document.getElementById("Power").value; var arr = [4.5, 5, 6.5] if (arr.includes(strength)) { document.getElementById("answer").innerHTML = ("result"); } else { document.getElementById("answer").innerHTML = ("nothing"); alert("Hello World"); } } </script> </body> </html>
Saturday, April 6, 2019 8:44 PM
Answers
-
User-943250815 posted
You can´t compare String with Number type, convert String to Number then compare
https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, April 6, 2019 10:56 PM -
User-2049827838 posted
Amended the offending line in the code to this and all is well
if (arr.includes(Number(strength))) {
Thanks guys
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Sunday, April 7, 2019 8:01 AM
All replies
-
User-943250815 posted
You can´t compare String with Number type, convert String to Number then compare
https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, April 6, 2019 10:56 PM -
User-2054057000 posted
I checked your code and did not find any problem. I have described the working of the cod below , check it:
var arr = [4.5, 5, 6.5] var strength = 4.5 console.log(arr.includes(strength)) // returns true
var arr = [4.5, 5, 6.5] var strength = 2 console.log(arr.includes(strength)) // returns false
Sunday, April 7, 2019 5:45 AM -
User-2049827838 posted
@jzero I thought JavaScript converted on the fly, that was why you didn't need to add a type when declaring a variable so didn't consider this an option but thanks, I'll check it out. It worked fine before I started using the text box so I'm guessing this is the problem.
@yogiyogi It worked fine for me when I first tested it in a similar way, that's why I was so confused.
Sunday, April 7, 2019 6:35 AM -
User-2049827838 posted
Amended the offending line in the code to this and all is well
if (arr.includes(Number(strength))) {
Thanks guys
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Sunday, April 7, 2019 8:01 AM