NodeJS如何循环查询

NodeJS How to loop through query

所以我是 Node 的新手,我确切地知道如何在 PHP 中做我想做的事,不过我在 Node 中。所以不知道。

我有以下内容。

switch(args[0]) {
    case 'games':
        var games = con.query("SELECT name FROM games");
        message.channel.send('Available Games:');
}

我的连接已经建立并且可以正常工作。我现在只想知道如何通过数据进行 foreach 以列出我想要的内容。

比如我在游戏中查询了名字,我想在回帖中显示所有的游戏名字。

我可以在这里foreach吗?完全不确定。

在 php 我会

foreach($games as $games) {//stuff here}

虽然这不起作用。

谢谢,

凯文

你在这里有很多选择,但我会提到最好的,

你可以使用地图(如果你想要 return 东西)

games.map(game=>{/*STUFF*/})

你可以使用 forEach(如果你不想 return 任何东西)

games.forEach(game=>{/*STUFF*/})

或"for of"

for (const game of game){/*STUFF */}

这一切都假设 games 是一个数组,但是您可以做一些事情:

如果您只想将游戏列表写入输出:

var games = con.query("SELECT name FROM games");
message.channel.send('Available Games:' + games.join(', '));

这相当于以下 PHP 代码:

$games = ['halo', 'call of duty', 'destiny 2'];
$message->channel->send('Available Games:' . implode(', ', $games));

如果您想遍历它们:

var games = con.query("SELECT name FROM games");
for (var i = 0; i < games.length; i++) {
    var game = games[i];
}

这相当于以下 PHP 代码:

$games = ['halo', 'call of duty', 'destiny 2'];
foreach ($games as $game) {
    // $game is in scope here
}

您还可以使用其他数组方法,例如 Array.forEach. But the scope is treated a little differently, and there can be a few gotchas. A lot of JavaScript devs will hate if you don't use the hip loops as opposed to good old fashioned for loops, but the performance with them is negligibly worse when dealing with small to medium size datasets and relatively the same on larger datasets