+ 4
JS ... Iâm trying to simplify this code, and Iâm not having a good time
Please look at the code, itâs something I need to explain in the code. The point is, Iâm trying to simplify the code so I donât have to do the same thing over and over again when Iâm trying to call a function(x, y, z){...} multiple times. https://code.sololearn.com/WfTCT1sO5U0S/?ref=app
11 Respostas
+ 5
Don't use eval. It's slow and unsafe. Just do:
function simplify(id){
return myFunc(x["user"+id].name, x["user"+id].age);
}
// Sinplified call
simplify(1)
simplify(2)
+ 4
I fixed it for you:
https://code.sololearn.com/WWeIzChqi4nJ/?ref=app
using the eval() function
The eval function is really useful because you can ârunâ strings if they contain JS code
+ 4
Ginfio My code works. I saved it on CodePlayground:
https://code.sololearn.com/Wzq1EEz4pJCp/?ref=app
Notice that "blablabla" is a string while blablabla is a name (undefined)
+ 4
Ginfio I see the problem. It requires only subtle changes.
First, the simplify() function below:
function simplify(userID){
return myFunc(x.userID.name, x.userId.age);
}
... completely ignores the input arg named userID. Instead, it tries to access the global object named x, using a property "x.userID" which is not defined. This is different from "x.user1" and "x.user2", which are defined.
The two args passed into myFunc() should be changed as follows:
Change:
{x.userID.name} to {userID.name}
{x.userId.age} to {userID.age}
NOTE: The "ID" in "userID" must match the casing in the parameter name. So... "userId" will be undefined.
Corrected Version:
----
function simplify(userID){
return myFunc(userID.name, userID.age);
}
----
Next, change the lines below from:
simplify(user1)
simplify(user2)
to:
simplify(x.user1)
simplify(x.user2)
Otherwise, user1 and user2 are undefined.
x.user1 and x.user2 are defined in the object called x. đ
https://code.sololearn.com/W69cR7rglctX/
+ 3
Ginfio I'm still confused. Can you provide a sample input and expected output?
This may be what you want:
function simplify (userID) {
return myFunc(x[userID].name, x[userID].age)
}
simplify("userone")
simplify ("usertwo")
+ 3
What do you mean by slow and unsafe?
+ 3
Kevin â
Sample code:
https://code.sololearn.com/W4AOq9gu244R/?ref=app
I tried your code, and it didn't seem to work.
+ 2
ok i see now/:
+ 1
Kevin â
Use the search bar
Forgot the number. thatâs not really what iâm worried about.
So itâs not confusing, letâs change the var to
userone
usertwo
userthree..
how would we do it if it wasnât like
user1, user2...
??
+ 1
My simplified answer đ
Hope it is simplified
https://code.sololearn.com/WwnkgqhbJBgA/?ref=app