1

So I am new to Node, I know exactly how to do what I want in PHP, I'm in node though. So no idea.

I have the following.

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

My connection is already set-up and working. I just wanna know how to foreach through the data now to list what I want.

For instance, since I queried name in games, I want to the message back to show all the game names.

Can I foreach here? Not sure at all.

in php I would just

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

That is not working though.

Thanks,

Kevin

KevinM1990112qwq
  • 715
  • 2
  • 10
  • 23
  • 1
    https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript – abelito May 23 '19 at 03:10
  • Possible duplicate of [For-each over an array in JavaScript?](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – T. Dirks May 23 '19 at 08:05
  • @T.Dirks Well it's not a duplicate. So.... – KevinM1990112qwq May 23 '19 at 08:06
  • @KevinM1990112qwq The main core of your question here is that you want to loop over an array of things (in this case names from a game database). The question I linked has answers which explain exactly that, how to loop over an array. It doesn't matter whether the data comes from an database or not – T. Dirks May 23 '19 at 08:22

2 Answers2

1

This all assumes games is an array, however you could do a few things:

If you just wanted to write the list of games into the output:

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

This would be equivilent to the following PHP code:

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

If you wanted to loop through them:

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

This would be equivilent to the following PHP code:

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

There are other array methods you can use such 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.

domdambrogia
  • 2,054
  • 24
  • 31
0

You have a lot of options here but I'll mention the best ones,

you can use map (if you want to return something)

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

you can use forEach (if you don't want to return anything)

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

or "for of"

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