带有变量的Javascript / Jquery访问对象

时间:2013-01-19 12:01:29

标签: javascript jquery arrays object

  

可能重复:
  Dynamic object property name

通过ajax调用,我收到一个对象:E

此对象包含许多子元素:widthheight等。

console.log (E.width)为我提供了E.width

的所有元素

当我指定var:tempElement = 'width'

为什么console.log(e.tempElement)返回'undefined'以及如何通过变量访问对象的子元素

$(function () {
    $('#widthSelect').on('change', function () {
        var updateArray = new Array();
        updateArray[0] = 'height';
        updateArray[1] = 'rim';
        updateArray[2] = 'load';
        updateArray[3] = 'speed';
        updateArray[4] = 'brand';
        updateArray[5] = 'season';
        getValues(updateArray);
    });

    function getValues(updateArray) {
        var data = updateArray.join('=&') + '=';
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '******',
            data: data,
            success: function (e) {
                element = updateArray[0];
                console.log(e.element);
            }
        });
    }
});

1 个答案:

答案 0 :(得分:2)

试试这个:

console.log( e[element] );

当你使用像e.element这样的“点符号”时,.之后的位将被视为属性名称。您的对象没有名为"element"的属性,因此您获得了undefined。如果使用数组样式表示法,方括号内的位将被计算为表达式,结果将用作属性名称。

e.width
// is equivalent to
e["width"] // note the quotation marks
// and equivalent to
someVariable = "width";
e[someVariable]
// and also equivalent to
e[someFunction()]  // assuming someFunction() returns the string "width"