简体   繁体   中英

Use javascript function parameter to get value from object

I have the following code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj.x);
};

When I run myFunction(apples) I don't get an alert saying five , but I get an alert saying undefined .

How do I get the result I want by using the function parameter x with the object myObj

The result I want is it to say 'five' instead of 'undefined' .

For getting a property with a string, you need to use brackets myObj["name"]

Look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Correct code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

Use [] notation:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction('apples')

You have to pass the property name as a string. And within a function use bracket notation ( [] ) for access instead of using a dot ( . ).

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction("apples");

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