[英]Using javascript function argument to return object value
Javascript function that takes a single argument. 带有单个参数的Javascript函数。 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. 在控制台日志中返回undefined的地方,JavaScript应该返回消息“ Hello bob”,因为someArg的值为“ bob”,调用message.bob返回正确的结果。
To print it properly, you'll have to: 要正确打印,您必须:
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: 现在,在调用someFunction('bob')时 ,输出为:
{"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. 您必须使用[]表示法,其中obj [key]与obj.key相同,但是key可以是变量。
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. 使用message.someArg
您是在“告诉”属性someArg或您的消息对象。
What you have to use is message[someArg]
to get the dynamic property. 您需要使用message[someArg]
来获取动态属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.