【发布时间】:2019-05-13 11:22:33
【问题描述】:
我在理解字典中选定数组的返回时有点麻烦。希望你能给我一个解释。顺便说一句,语言是javascript。
我创建了一个字典,其中包含一些数组作为值。当使用正确的键选择值时,我的输出是一个包含我的数组值的数组。我期待直接获得我的数组值。
编辑:字典的创建似乎是问题所在。假设两个字典相同。 这里是日志的截图: chromelog
var dictionary1 = {"key1" : ["element10","element11"], "key2":["element20","element21"]};
$.each($(".select-filters"),function(i,v) { //select all filters
if (dic_results[$(this).attr("name")] == null) { // if the list don't exist create it
dic_results[$(this).attr("name")] = []
}
dic_results[$(this).attr("name")].push($(this).val()); //push the value inside the array
});
console.log(dictionary["key1"]); //return the correct value ["element10",element11"]
console.log(dic_results["key1"]);//return [Array(1)] expecting ["element10",element11"]
console.log(dic_results["key1"][0]);//return ["element10",element11"]
【问题讨论】:
-
@trincot 它仍然很奇怪 - 如果未定义
key1,我预计会出错。或者如果是,那么我不希望它返回Array(1)。我认为 OP 在这里缺少一些信息。 -
key1的值是多少?不确定dictionary[key1]如何返回[["element10",element11"]]?这不是minimal reproducible example -
dictionary是否有类似这样的吸气剂:Object.defineProperty(dictionary, <key1's value here>, { get() { return [this["key1"]] } }) -
您可能在回调中使用了错误的
this。不记得太多 jquery 但尝试使用$(".select-filters").each(..). -
等等,is this it?您的 HTML 中有多重选择吗?
标签: javascript jquery arrays dictionary