JavaScript: Constructing an array composed of multiple arrays

I am attempting to create an array containing four arrays. Each of these four arrays will contain three numbers, with two of them being randomly selected from a set of numbers.

Although I am not encountering any errors when running the code below, I am also not receiving the expected result. What could be the issue?
The console.log printout is just for verification purposes, I am primarily focused on constructing the array 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();

Answer №1

Don't forget to retrieve your foe :)

function spawnEnemy() {

  var yPositions = [80,160,240];    
  var speeds = [25,35,50,55];  

  var randomY = Math.floor(Math.random() * yPositions.length);
  var randomSpeed = Math.floor(Math.random() * speeds.length);

  var enemyStats = [yPositions[randomY], speeds[randomSpeed], x];

  return enemyStats;
}

Answer №2

Ensure that you have a return statement in your createEnemy function:

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

You may also find this loop to be more efficient than the nested one you currently have:

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

Answer №3

It appears that the createEnemy function is missing a 'return enemy' statement and there is an unnecessary tertiary level loop in the code. Below are some modified lines with improved indentation for better readability:

UPDATED 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 statement for 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) {
    console.log(allEnemies[j].join(' ')); // Simplified to avoid nested looping
  }

}

printEnemies();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for effectively parsing extensive nested JSON structures?

JSON Data on PasteBin I need assistance in converting this JSON data into an Object. It seems valid according to jsonlint, but I'm encountering issues with parsing it. Any help would be greatly appreciated. "Data":[{...},{...},] // structured like t ...

Utilizing 'document.execCommand' for handling 'delete' key events in AngularJS

Here is a demo plunkr link that I have created to demonstrate the issue. I am looking to implement the strikeThrough command whenever there is a delete operation. For instance: If the user selects "Text" and presses the delete or backspace key, it should ...

AngularJS encounters an issue while attempting to print a PDF file

I am encountering an issue with printing a PDF file that was generated using reportViewer in my Web API. The browser displays an error when attempting to open the PDF file. Below is the code snippet from the controller in my Web API: // ...generate candi ...

Node.js is throwing an error when attempting to delete a post using a hyperlink: "Cannot

Utilizing a hyperlink to remove a project from my main.ejs template is causing an issue when I click on the delete option. It shows an error message saying "Cannot GET /delete/6424f79c7dd4cd07ef49acae". Below is the code snippet for the delete hyperlink: ...

Dynamic element not firing jQuery event

My question is...https://i.sstatic.net/me2uQ.png // Using ajax to dynamically create a table $(".n").click(function(){ var id= $(this).closest('tr').find('td.ide2').html(); //for displaying the table $.ajax({ ...

Is it possible to modify the color of each HTML division individually, with a delay of 500 milliseconds for each

I have been struggling with dom manipulations in a sorting visualizer game I am developing using Vanilla JS and HTML/CSS3. Specifically, I am having difficulty implementing color changes for each div at a particular time interval of 500ms. How can I succ ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

How can I implement user-specific changes using Flask?

I am a beginner with Flask and I am working on a project where users can sign up, and if the admin clicks a button next to their name, the user's homepage will change. Below is the Flask code snippet: from flask import Flask, redirect, url_for, render ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

"Utilize Azure Storage to easily upload an image file and retrieve its URL for seamless display using the img

I am looking to utilize Azure file storage for storing image files. I have the ability to upload an image file using the code snippet below: ... const uploadBlobResponse = await blockBlobClient.uploadFile('./test.png'); console.log('Blob was ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Navigating Through Tabs in Bootstrap 4

I am currently working on a scrolling tab feature and encountering an issue. I am unable to click on the middle tabs as the scrolling movement is too abrupt when using the right button. How can I adjust the code to allow for a smoother scroll of the tabs? ...

What is the reason behind the array.push() method not altering the array?

Here's the challenge: Eliminate all falsy values from a given array. Falsy values in JavaScript include false, null, 0, "", undefined, and NaN. Tips: Try converting each value to a Boolean. Below is my attempt at solving it: function bouncer(a ...

Tips for updating a div element while maintaining its style and select2 plugin functionality with jQuery

Within the HTML code, I am attempting to refresh the following div: <select name="test[]" id="test" multiple required class="select2"> @foreach($tests as $s) ...

Sharing variables between server.js files - a step-by-step guide

I am currently in the process of creating a sleek weather webpage. I have successfully retrieved weather data from the Open Weather API through a Node.js server file. However, I have encountered an issue where I am unable to pass a variable, such as tempe ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Utilizing an SSL certification (pem file) within JavaScript

Currently in the process of developing a program to extract data from the FAA's AIDAP database. I received a security certificate in the form of a .p12 file, which I have successfully converted into a .pem file. However, I am encountering difficulties ...

Is there a universal function that can handle multiple arrays with the same data types in C programming?

I need to create a versatile function that can work with multiple arrays of different sizes but the same datatypes, and only takes the array number as an argument. Let's assume we have three arrays: arr1[10], arr2[15], arr3[20]. The desired generic fu ...

When the icon is clicked, initialize the jQuery UI Datepicker

Here is the code I am working with in a Backbone view: <input type="text" id="fromDate" name="fromDate"/><a id="cal"> <img src="img/calendar.gif"></a> Within the view's JavaScript file, I have implemented the following: defi ...

Troubleshooting Problems with Wordpress Shortcode Arrays

Here is an example of how a shortcode appears: [posts3col ids="249, 318, 93" category="Events"] Below is the code related to the shortcode: add_shortcode('posts3col', 'posts_func'); function posts_func($atts){ extract(shortcode_a ...