简体   繁体   English

使用javascript函数参数从对象获取值

[英]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 . 当我运行myFunction(apples) ,没有得到警告,说five ,但是却得到了警告,说undefined

How do I get the result I want by using the function parameter x with the object myObj 如何通过将函数参数x与对象myObj一起使用来获得所需的结果

The result I want is it to say 'five' instead of 'undefined' . 我想要的结果是说'five'而不是'undefined'

For getting a property with a string, you need to use brackets myObj["name"] 要获取带有字符串的属性,您需要使用方括号myObj [“ name”]

Look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors 查看以下内容: https : //developer.mozilla.org/zh-CN/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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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