Javascript: creating an array of arrays

I am trying to create an array of four arrays. Each of these four arrays consists of three numbers, two of which are randomly assigned from a set of numbers.

When I run the following code, I do not get the error, but I also do not get the result. What am I missing?
I really don't need a listing in console.log, it's just a check that the array is being built correctly.

var x = -2;

function createEnemy(){

var yArray = [60,145,230];    
var speedArray = [30,45,55,60];  

var randY = Math.floor(Math.random() * yArray.length);
var randSpeed = Math.floor(Math.random() * speedArray.length);

var enemy = [yArray[randY], speedArray[randSpeed], x];

}


function printEnemies()
{

var allEnemies = [];
(function setEnemies()
{
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
allEnemies.push(createEnemy());
}());


for(var j in allEnemies)
{
for(var p in allEnemies[j] )
{
    for(var i = 0; i < allEnemies[j][p].length; i++ )
    {
         console.log(allEnemies[j][p][i]);
    }
 }
}

}

printEnemies();

+4
source share
3 answers

You forgot to return yours enemy:)

function createEnemy() {

  var yArray = [60,145,230];    
  var speedArray = [30,45,55,60];  

  var randY = Math.floor(Math.random() * yArray.length);
  var randSpeed = Math.floor(Math.random() * speedArray.length);

  var enemy = [yArray[randY], speedArray[randSpeed], x];

  return enemy;
}
+4
source

Make sure you return something from createEnemy:

return [yArray[randY], speedArray[randSpeed], x];

Alternatively, you might prefer something like this loop for your nested one:

allEnemies.forEach(function (arr) {
  console.log(arr[0], arr[1], arr[2]);
});
+1

, " " createEnemy, . ( ).

CODE

var x = -2;

function createEnemy() {

  var yArray = [60,145,230];    
  var speedArray = [30,45,55,60];  
  var randY = Math.floor( Math.random() * yArray.length );
  var randSpeed = Math.floor( Math.random() * speedArray.length );
  var enemy = [yArray[randY], speedArray[randSpeed], x];
  return enemy;  // Added a return of the enemy.

}


function printEnemies() {

  var allEnemies = [];
  ( function setEnemies() {
    allEnemies.push(createEnemy());
    allEnemies.push(createEnemy());
    allEnemies.push(createEnemy());
    allEnemies.push(createEnemy());
   }()
  );

  for(var j in allEnemies) {
    for(var p in allEnemies[j] ) {
      console.log (allEnemies [j][p] ); // Removed additional depth of loop
    }
  }

}

printEnemies();
+1
source

Source: https://habr.com/ru/post/1619673/


All Articles