我在尝试从JavaScript函数中获取返回的数组时遇到了一些问题。这是代码:
var circle;
var eventNameList = [];
function doBuffer(pos) {
$.ajax({
url: "/TogetherSG/TogetherServlet?action=GetEvents",
type: "GET",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, jsondata) {
showBuffer(p1,p2, eventName, eventDesc, eventVenue);
getChart();
});
},
error: function (request, state, errors) {
}
});
}
基本上doBuffer()将从MySQL获取所有事件并将每个事件传递给showBuffer以执行计算。
function showBuffer(p1, p2, eventName, eventDesc, eventVenue) {
// Calculation for distance between two points
var distance = (google.maps.geometry.spherical.computeDistanceBetween(p1,
p2) / 1000).toFixed(2);
eventNameList.push(eventName);
}
}
对于showBuffer,我正在计算距离的每个点。如果距离小于1,那么我将该点推入阵列。
然后从我从上面的第一个函数调用的getChart():
function getChart(){
console.log(eventNameList);
}
我打印出列表。但是,我得到的结果为:
[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
["Event4"] events.js:202
["Event4", "Event5"] events.js:202
["Event4", "Event5", "Event6"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"]
我想知道怎么循环这么多次。因为从返回的结果中,我需要以这种方式将其格式化为字符串:
'Event4','Event5','Event6','Event7'
但我不确定我应该何时何地格式化它。有什么想法吗?
提前致谢。
答案 0 :(得分:0)
要从包含这些单个单词作为元素的数组中获取所需的'Event4','Event5','Event6','Event7'
字符串格式,您只需使用join
','
数组元素,然后添加缺失正面和背面'
如下:
var desiredStringFormat = "'" + yourArray.join("','") + "'";
答案 1 :(得分:0)
getChart函数只是在构建数组时记录eventNameList的控制台。如果将getChart函数移出循环,它将仅在完成循环后记录数组。您可以将它放在循环之后,在AJAX之后,或者除了它现在之外的任何地方,它将显示正常。你正在看你的代码在行动,你的眼睛正在玩弄你。