简体   繁体   中英

Using javascript function argument to return object value

Javascript function that takes a single argument. Use that argument value which is a string to return the appropriate value from the matched object key.

 function someFunction(someArg) {

var message = {
    bob: "Hello bob",
    mike: "Hello mike",
    tara: "Hello tara"
}

console.log(message +  " " + message.someArg + " " + someArg + " " + message.bob);

}

what is returned is

 [object Object] undefined bob Hello bob

Where undefined is returned in the console log, JavaScript should return the message "Hello bob" as the value of someArg is "bob", calling message.bob returns the correct result.

To print it properly, you'll have to:

  • Stringify the message object
  • Refer to the property of message in a correct manner

Try this

function someFunction(someArg) {
   var message = {
    bob: "Hello bob",
    mike: "Hello mike",
    tara: "Hello tara"
   }
   //ES6
   console.log(`${JSON.stringify(message)} ${message[someArg]} ${someArg} ${message.bob}`);
   //ES5
   console.log(JSON.stringify(message) +  " " + message[someArg] + " " + someArg + " " + message.bob);

}

Now, on calling someFunction('bob') , the output is:

{"bob":"Hello bob","mike":"Hello mike","tara":"Hello tara"} Hello bob bob Hello bob

You have to use the [] notation, where obj[key] is the same as obj.key, but key can be a variable.

 function someFunction(someArg) { var message = { bob: "Hello bob", mike: "Hello mike", tara: "Hello tara" } console.log(JSON.stringify(message) + " " + message[someArg] + " " + someArg + " " + message.bob); } someFunction("mike"); 

When using message.someArg you are "telling" attribute someArg or your message Object.

What you have to use is message[someArg] to get the dynamic property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM