Why does this code work with integers but not with strings? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

Why does this code work with integers but not with strings?

https://code.sololearn.com/WxvI8a32AXFA/?ref=app Can someone help me fix it? Thank you.

19th Mar 2019, 3:30 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
5 Answers
+ 5
💧Alex Tusinean🔥, JS-in doesn't work like Python-in: It asks for the key in key-value pairs. (Or maybe, JS arrays react to in more like Python's dicts react to in.) In a simple array, your 'keys' are digits (indexes) which are accidentally equal to the values, so it works, but in the other function, in still asks for the indexes. If you want something like Python's in, something that asks for the values, take the method includes! if (hi.includes( document.getElementById( "inp2").value) )
19th Mar 2019, 6:09 PM
HonFu
HonFu - avatar
+ 8
// try this: // I tried it and it worked if (~hi.indexOf(document.getElementById("inp2").value) ){ alert("work") } }
19th Mar 2019, 5:46 PM
VEDANG
VEDANG - avatar
+ 8
Because you must specify index in object, but not the value of that index. Not literal of array, but constructor Array. But index instead of value let foo = new Array("one", "two"); 0 in foo // true "length" in foo // true (Array has this property) "one" in foo // false
19th Mar 2019, 6:35 PM
Вап
+ 7
Thank you all! After all , I use HonFu solution. Thank you for the explication , I tried to do this code using "in" as I used in Python.
19th Mar 2019, 6:49 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 2
I made the same mistake. 😑😅
19th Mar 2019, 6:51 PM
HonFu
HonFu - avatar