Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用变量遍历对象_Javascript_Html_Syntax - Fatal编程技术网

Javascript 使用变量遍历对象

Javascript 使用变量遍历对象,javascript,html,syntax,Javascript,Html,Syntax,我想我真的不知道如何问这个问题来找到答案 所以我有三个变量,它们将使这个函数做它必须做的事情 function gatherDataForGeographic(ele) { var $this = $(ele) var $main_title = $this.find('.options-title'), $option = $this.find('.option'); var arr = [] va

我想我真的不知道如何问这个问题来找到答案

所以我有三个变量,它们将使这个函数做它必须做的事情

    function gatherDataForGeographic(ele) {
        var $this = $(ele)
        var $main_title = $this.find('.options-title'),
            $option = $this.find('.option');
        var arr = []
        var reportAreas = reportManager.getReportAreasObject();


        $option.each(function () {
            var $this = $(this)
            var $checkbox = $this.find('.checkbox');
            var type = $this.data('type'),
                index = $this.data('index');

            if ($checkbox.hasClass('checkbox--checked')) {
                console.log(reportAreas.type)
            } else {
                return true;
            }
        })
        return arr;
    }
    //this will return an object that I need to index  
    var reportAreas = reportManager.getReportAreasObject();

    //this will get the a key that i need from the object 
    var type = $this.data('type');

    //this will give me the index I need to grab
    var index = $this.data('index');
因此,我试图根据用户选择的选项中的类型(或键)遍历对象

问题是。。。 它正在寻找
reportArea.type[index]
,但没有将其识别为变量,我一直得到
未定义的
,因为.type不存在


有没有办法让它看到类型是变量而不是键

您可以使用括号语法而不是点语法在JS中使用动态属性:

reportAreas[type]

这将解析为
reportAreas['whateverString']
,相当于
reportAreas。whateverString
-
reportAreas.type
但是,它是对
type
属性的文本检查。

您可以使用括号语法而不是点语法在JS中使用动态属性:

reportAreas[type]
reportArea[type][index]
这将解析为
reportAreas['whateverString']
,相当于
reportAreas。whateverString
-
reportAreas.type
但是,它是对
type
属性的文本检查

reportArea[type][index]
JavaScript对象只是键值对,点语法只是数组符号的语法糖

object['a']

基本上是一样的

JavaScript对象只是键值对,点语法只是数组符号的语法糖

object['a']


基本上都是一样的。

哦,太好了,那很容易。非常感谢你!如果时间允许,我会接受这个答案。哦,太好了,那很容易。非常感谢你!如果时间允许,我会接受这个答案。