0

What Is Wrong With This Code?

Hey, im a noob, and I kinda need help. This is the code I wrote: <script> function Y() { var _user = []; var _user[p1] = wyuw; var _user[p2] = ethan; var x = prompt("Enter Username"); if(x === _user[p1]){ alert("wyuw"); } else if(x === _user[p2]){ alert(ethan); } else{ alert("Error"); } } </script> <body> <button onclick="Y()">Test</button> </body> Its not working, can someone give me a working copy?

9th Jul 2017, 5:31 PM
❮вαιι–кιηgz❯ dario
❮вαιι–кιηgz❯ dario - avatar
7 Answers
+ 7
Complete fixed code: function Y() { var _user = {}; _user['p1'] = 'wyuw'; _user['p2'] = 'ethan'; var x = prompt("Enter Username"); if(x === _user['p1']){ alert("wyuw"); } else if(x === _user['p2']){ alert('ethan'); } else{ alert("Error"); } } (edit: don't use 'var' keyword when assigning item to array or object, and enclose all your strings in quotes -- simple or double)
9th Jul 2017, 5:56 PM
visph
visph - avatar
+ 5
Yes: I've post too quickly ;P It's your lines setting values for _user array that have mistakes: + right part of the assignement need to be embeded in quotes to set string literals + left part need to be indexed with integer if you use an array, else you need to use object: _user = {}; // create a new object (key/value list) _user['p1'] = 'wyuw'; _user['p2'] = 'ethan'; Without enclosing strings in quotes, JS search a variable named so, but doesn't find any (undefined)...
9th Jul 2017, 5:52 PM
visph
visph - avatar
+ 4
You only define a function, but never call it, so it's never executed ^^ Add: Y(); To execute the function ;)
9th Jul 2017, 5:44 PM
visph
visph - avatar
+ 2
Thanks for the help guys! I appreciate it.
9th Jul 2017, 5:58 PM
❮вαιι–кιηgz❯ dario
❮вαιι–кιηgz❯ dario - avatar
+ 1
you must enclose wyuw and ethan in quotation marks (lines 3, 4 and 10)
9th Jul 2017, 5:42 PM
Andrés04_ve
Andrés04_ve - avatar
+ 1
@visph he is running it with a button event
9th Jul 2017, 5:45 PM
Andrés04_ve
Andrés04_ve - avatar
0
Yay! It worked! TYSM Visph.
9th Jul 2017, 6:01 PM
❮вαιι–кιηgz❯ dario
❮вαιι–кιηgz❯ dario - avatar