Javascript推送对象到数组不工作

时间:2015-09-06 19:44:16

标签: javascript arrays node.js object

我正在使用node mirc从mysql中检索数据

enter image description here

然后我希望使用以下代码将数据转换为数组:

function getQuestion (arr{
    var obj = {};

    connection.connect();
    connection.query("SELECT * FROM quiz", function (err, rows, fields) {
        if (err) throw err;

        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
            f100.push(obj);
        };
    });
    connection.end();
}
f100 = [];
getQuestion();
console.log(f100);

但是,它只打印[]

2 个答案:

答案 0 :(得分:1)

connection.query是异步的,因此我建议在f100回调中安排connection.query。如果您希望在完成填充后对f100执行某些操作,则需要将其从连接查询回调中传递到另一个函数中。例如:

connection.query("SELECT * FROM quiz", function (err, rows, fields) {
    if (err) throw err;

    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
        f100.push(obj);
    };

    console.log(f100); // should console out correctly here
    handleArray(f100); // passes in f100 to a new function
});

答案 1 :(得分:1)

由于.query()'s异步行为,它需要一些时间来执行,但您在调用该函数后立即执行日志。您需要使用.query()函数的回调来记录日志。

function getQuestion (arr{
    var obj = {};

    connection.connect();
    connection.query("SELECT * FROM quiz", function (err, rows, fields) {
        if (err) throw err;

        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            obj = {"id":row.id, "question":row.question, "answers":row.answers.split(", ")};
            f100.push(obj);
        };

        // do log here
        console.log(f100);
    });
    connection.end();
}
f100 = [];
getQuestion();