【问题标题】:Can't pass object property name through function parameter无法通过函数参数传递对象属性名称
【发布时间】:2018-07-31 22:38:25
【问题描述】:

我试图通过函数参数传递对象属性名称,但它不起作用。这是我的脚本(详细信息如下):

<!DOCTYPE html>
<html>
<body>
<button onclick="myButton()">Try it</button>

<p id="display"></p>
<p id="display2"></p>

<script>

var person = {"name":"dupont","surname":"bob"};

function myButton() {    
    document.getElementById("display").innerHTML = person.name;    
    function personInfoDetails(x) {
    document.getElementById("display2").innerHTML = person[x];
    }
    personInfoDetails(name);
}

</script>

</body>
</html>

我想通过函数“personInfoDetails(x)”显示“dupont”,即我的对象“person”的属性“name”下的存储值。为此,我执行此函数,通过对象“person”的属性“name”替换其参数“x”。但它显示“未定义”。

这是live preview of this script

我已经准备好阅读this post 并尝试将其解决方案应用于我的问题,但它仍然不起作用。

非常感谢您的解决方案!

【问题讨论】:

    标签: javascript arrays json properties parameter-passing


    【解决方案1】:

    您需要用引号 ""name 括起来

    var person = {
      "name": "dupont",
      "surname": "bob"
    };
    
    function myButton() {
      document.getElementById("display").innerHTML = person.name;
    
      function personInfoDetails(x) {
        document.getElementById("display2").innerHTML = person[x];
      }
      personInfoDetails("name");
    }
    <!DOCTYPE html>
    <button onclick="myButton()">Try it</button>
    <p id="display"></p>
    <p id="display2"></p>

    【讨论】:

    • 哇!我从几个小时开始就一直在解决这个问题(我是一个 js 编程初学者)。这就是解决方案...添加引号...非常感谢!并感谢您的快速答复。很酷
    • 是否也可以使用不带引号的参数“name”调用函数 personInfoDetails()?这样做(我知道我的代码不起作用,但这是为了解释我的想法):function personInfoDetails(x) { var y = " + x + "; document.getElementById("display2").innerHTML = person[y]; } personInfoDetails(name);
    • @mosis 否,因为编译器无法找到变量name。此外,这是不正确的var y = " + x + "
    • 好的,非常感谢。我希望通过一些字符串操作,将输入的参数 name ( personInfoDetails(name); )转换为 "name " 我可以用它来显示我的对象 person 的相应内容
    猜你喜欢
    • 2011-11-06
    • 2020-07-12
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多