4

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

When I run the following code I don't get an error, but I also don't get a result. What am I missing?
I don't really need the print out in console.log, this is just to check if the array is constructed 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();

0

3 Answers 3

4

You forgot to return your 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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Make sure you return something from createEnemy:

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

Also, you might prefer something like this loop to the nested one you've implemented:

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

Comments

1

Looks like you're missing a 'return enemy' from the createEnemy function and you have an unnecessary tertiary level loop. Here's some modified lines (with some indentation updates for readability).

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.