+ 2
[JAVASCRIPT] User input's falsey values on Playground [CLOSED]
Please, check this code: https://code.sololearn.com/WhQky7gGMgWE/#js I can't make the input work after getting the values from the getElementById. I've split them into an array, but, it doesn't work either. The function works if I test it with the test cases commented there. Can you help me?
9 Respuestas
+ 4
A hint. Insert this at line 4:
alert(typeof arr)
This may not be the best/right suggestion, but you may need an intermediate eval()
+ 4
I'm trying not to directly give you the answer here, because discovering this with a little "work on you" sometimes helps, but I don't know for sure eval() is best*, so:
input:
['a', 'b', 'c']
alert(typeof arr)
--> string
arr=eval(arr);
alert(typeof arr)
--> object
The second object is an array and does what you expect (including having the correct method to call). For strings, I believe only the empty string is Falsey.
* Entering javascript would run the code, for example.
+ 4
To clarify:
'["a", False, True, 1]' --> a string, is Truthy (but crashes because it doesn't have the methods you want)
["a", False, True, 1] --> a javascript array object after eval(string)
+ 3
[1] Even without your input type of "text", for input.value I'm only seeing recommendations to use parseInt, parseFloat, valueAsNumber ... (etc) to convert it from string to another Javascript object.
[2] Similarly, in the first comment, input "innerHTML always returns a string", with recommendations to "parse as integer" (etc) in other answers.
[3] Whereas .filter is a method on arrays (and not strings)
[4] Arrays also have a ".from(other type)" method
If you aren't allowed to parse the user's input at all, you could give people a selection list and then when they choose an item, an object of the right type is returned. Given how long it's taken me to get here, I could show a short example of that.
[1] https://stackoverflow.com/questions/27849944/input-value-is-a-string-instead-of-a-number
[2] https://stackoverflow.com/questions/21940513/type-of-html-element-returned-from-document-getelementbyid-string-not-number
[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
[4] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
+ 3
really appreciated my friend.
+ 2
Thank you, Kirk. I can't see how to do it, but don't worry.
It's obviously me. Not your explanations.
+ 1
Thank you, Kirk. But, the problem is not with the output, but the input. The point of the function is to use filter() and to filter by Boolean. I can't get the user's input right. Not sure if I'm explaining myself.
+ 1
Thank you, Kirk. But I must use filter() in this example.
+ 1
I may just be choosing the wrong bridges. It happens. Hope you get it by your efforts / an answer better for you :)