过去两天我一直在努力解决这个问题,请帮助我。
我有一个具有以下结构的json文件,我使用jQuery getJSON来检索json文件:
{"locations":[
{"gov": "Riyadh", "city": "Riyadh", "coordinates": [24.7135517, 46.67529569999999, 5.78], "img": "riyadh.jpg"},
{"gov": "Dammam", "city": "Dammam", "coordinates": [26.340680925140543, 50.1088628919922, 5.81], "img": "dammam.jpg"},
{"gov": "Makkah", "city": "Makkah", "coordinates": [21.39988519210946, 39.8476324232422, 11], "img": "makkah.jpg"},
{"gov": "Makkah", "city": "Jeddah", "coordinates": [21.295001497070977, 39.2214117201172, 9], "img": "jeddah.jpg"
}]
}
我有以下JS:
function getJsonResults(p,prop=null) {
var temp= [];
var obj= {pro: prop};
$.getJSON(p,obj, function(data) {
var jsonResults= data.locations;
var x = obj.pro;
// loop through the results I got from some answers here in stackoverflow
Object.keys(jsonResults).forEach(function(key) {
//get the value of name
var val = jsonResults[key][x];
//push the name string in the array
temp.push(val);
});
// this is how I did looping earlier
// for(var i = 0; i< jsonResults.length; i++){
// if (prop==null) {
// temp.push(jsonResults[i]);
// }else{
// temp.push(jsonResults[i][x]);
// }
// } // end for
});
return temp;
}
var landsJson = 'assets/js/locations.json';
var govs= getJsonResults(landsJson,"gov");
var govsNoDup= ArrNoDupe(govs);
这很好但是当我在控制台中检查它时它看起来不像常规数组,即(3)[1,2,&#34; k&#34;]它显示为[]和何时我尝试将它用作另一个函数的参数,例如删除重复项,它返回一个空数组。
我对javascript不太熟悉,但我觉得问题是它返回的对象不是常规的字符串数组值。