繁体   English   中英

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

[英]Use javascript function parameter to get value from object

我有以下代码:

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

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

当我运行myFunction(apples) ,没有得到警告,说five ,但是却得到了警告,说undefined

如何通过将函数参数x与对象myObj一起使用来获得所需的结果

我想要的结果是说'five'而不是'undefined'

要获取带有字符串的属性,您需要使用方括号myObj [“ name”]

查看以下内容: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors

正确的代码:

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

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

使用[]表示法:

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

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

myFunction('apples')

您必须将属性名称作为字符串传递。 在函数中,请使用方括号( [] )进行访问,而不要使用点( . )。

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