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']
及
基本上都是一样的。哦,太好了,那很容易。非常感谢你!如果时间允许,我会接受这个答案。哦,太好了,那很容易。非常感谢你!如果时间允许,我会接受这个答案。