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?
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)
+ 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)...
+ 4
You only define a function, but never call it, so it's never executed ^^
Add:
Y();
To execute the function ;)
+ 2
Thanks for the help guys! I appreciate it.
+ 1
you must enclose wyuw and ethan in quotation marks (lines 3, 4 and 10)
+ 1
@visph he is running it with a button event
0
Yay! It worked! TYSM Visph.



