简体   繁体   中英

How to access the value of a property of an object using a function in Javascript?

Just learning JS and I'm working through some tutorials. I've ran into a question that I have not been able to solve. The question is:

Write a function called getValue() . It should take two inputs: an object and a key . It should return the corresponding value for that key within the object . Keep in mind that this should be a one-line function .

I know you can access this with objectName.property but I haven't been able to figure out how to do this within a function .

Again, very new to JS . Any help would be greatly appreciated!

Basically, you need a function with a name, which is

function getValue() {
}

Then you need the parameters, like object and key , which are written in the head of the function.

function getValue(object, key) {
}

After that, you need to return something. This stops the function as well.

function getValue(object, key) {
    return;
}

At last, you need the value from the object with a property accessor with bracket notation, it take the object and a variable, or a value for the key, like

object[key]

and together in the function, you get then

function getValue(object, key) {
    return object[key];
}

In the case, you supply a key, which is not in the object, you get undefined as result.

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