Javascript 指向一个对象属性

Javascript point to an object property

本文关键字:属性 一个对象 Javascript      更新时间:2023-09-26

我有一个这样的数组:

   elements = new Array(
       {opinions: 'p31/php/endpoint.php?get=opinions'}, // function to call and API endpoint, php/endpoint.php
       {top3positive: 'p31/php/endpoint.php?get=top3positive'}, // function to call andAPI endpoint, php/endpoint.php
       {top3negative: 'p31/php/endpoint.php?get=top3negative'} // function to call andAPI endpoint, php/endpoint.php
        );

我试图获得价值。例如,简单的事情是:elements[0].opinions将正确返回p31/php/endpoint.php?get=opinions事实是,我需要在不直接知道值的情况下获取相同的信息。

所以我正在做以下事情:

function getEndPoint(element) {
    for (index in elements) {
        if (Object.getOwnPropertyNames(elements[index]) == element) {
            console.log(eval(elements[index]. element));
        }
    }
}

例如,element代表意见。当我这样做console.log(eval(elements[index]. element));它没有正确返回p31/php/endpoint.php?get=opinions而是返回未定义。我还尝试使用eval()来评估从字符串到可运行代码的element,但什么都没有。

我做错了什么?谢谢

使用

elements[index][element]

但这不正是你想要的吗?

elements[element]

另外,使用 === 而不是 ==...