我正在开发一个网络应用,我遇到了一个问题。我简化了这个问题。我在全局声明一个数组,即在循环之外。当我将数据推入其中然后我在循环结束时输出该数组并在循环外部返回空数组,为什么会这样。即使我在循环中输出数据它也会返回推送数据,但是在循环之外它会返回声明的空数组,这意味着没有数据被推送到它。
var last_data = [],
last_time, last_text;
for (var i = 0; i < res.length; i++) {
var GET_LASTMESS_AND_TIME = "SELECT username,mess_txt,mess_time FROM (select mess_to as user_id,mess_txt,mess_time from messages where mess_from = '" + res[i].id + "' AND mess_to='" + data + "' UNION select mess_to as user_id,mess_txt,mess_time from messages where mess_from = '" + data + "' AND mess_to='" + res[i].id + "') sq join users on users.id = sq.user_id";
con.query(GET_LASTMESS_AND_TIME, (e, r) => {
if (e) throw e;
var len = r.length;
last_time = r[len - 1].mess_time;
last_text = r[len - 1].mess_txt;
last_data.push({
date: last_time,
text: last_text
});
socket.emit("user_messages_list", {
result: res,
last_data: last_data
});
});
}
console.log(last_data);
&#13;
当我尝试下面的示例示例时,它会返回已推送到它的数据。
var data = [],
a, b;
for (var i = 0; i < 10; i++) {
a = i + 10;
b = i + 20;
data.push({
val1: a,
val2: b
});
}
console.log(data);
&#13;