Using a for loop to populate a two-dimensional array in JavaScript

Currently, I'm attempting to populate a two-dimensional array in JavaScript using the following method:

var i = 0, j = 0;
for (i = 0; i < roomWidth / tileWidth; i += 1) {
     roomBuffer[i] = [];
}
for (i = 0; roomWidth / tileWidth; i += 1) {
     for (j = 0; j < roomHeight / tileHeight; j += 1) {
          roomBuffer[i][j] = 1;
     }
}
alert("Hello world");

The issue I'm encountering is that not only does this code fail to execute properly, but it also prevents any subsequent code from running. For example, the alert("Hello world"); does not appear. Could someone please advise on where I may be going wrong?

Answer №1

update

for (i = 0; roomWidth / tileWidth; i += 1) {

to

for (i = 0; i < roomWidth / tileWidth; i += 1) {

Answer №2

Declaring i and j before the loops is unnecessary. If they are only needed within the loops, it's better to define them as local variables. Additionally, you can optimize by combining loops.

I agree with @Yuriy Zubarev's point that the middle statement in the for-loop must remain true throughout the entire loop execution.

for (var i = 0; i < roomWidth / tileWidth; i++) {
     roomBuffer[i] = [];
     for (var j = 0; j < roomHeight / tileHeight; j++) {
          roomBuffer[i][j] = 1;
     }
}
alert("Greetings universe");

Answer №3

Take a look at this code snippet.

Update your

for (i = 0; roomWidth / tileWidth; i += 1)

to

for (i = 0; i < roomWidth / tileWidth; i += 1)

Answer №4

If you want to streamline your code, consider incorporating a compact helper function

// generate an array of specified length filled with a specific value
populateArray = function(length, val) {
    for (var arr = []; length-- > 0; arr.push(val));
    return arr;
}

Your current code snippet:

numTiles = roomWidth / tileWidth
roomLayout = populateArray(numTiles, populateArray(numTiles, 1))    

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

Discovering the geographical location of all users using Node.js: A step-by-step guide

My current task involves determining the geoip location of users. I have implemented a code that stores the user's address in the database and then displays the geoip location accordingly. However, if a user changes their location and logs in from a d ...

How is it possible for the javascript condition to be executed even when it is false?

Despite the condition being false, the javascript flow enters the if condition. Check out the code snippet below: <script> $(document).ready(function() { var checkCon = "teststr2"; console.log("checkCon: "+checkCon); if(checkCon == " ...

How to send out an Array and a Variable at the same time using socket.io

Currently expanding my knowledge with Node.js, Express.js, and Socket.io. I successfully created a chat application that is functional at the moment. Now I am interested in letting the Client know when a user enters or exits the chat by emitting a variab ...

Querying two MongoDB collections simultaneously to locate a user based on their email address

I am working with two different collections, tutors and users, within my MongoDB database. Within the controller, I have a function called signin. In this function, I need to modify the condition so that it searches for a user in both the tutors and users ...

Tips on completing landing page animations and displaying the main page of a website by utilizing React JavaScript

https://i.stack.imgur.com/M4VgY.pngIs there a way to stop the landing page animation after 2-3 seconds and show the main page instead? Can I achieve this by using setTimeOut function in JavaScript? [ export default Loader; ...

Is there a PHP function that functions similarly to JavaScript's "array.every()" method?

As I work on migrating JavaScript code to PHP, I am facing the challenge of finding a replacement for the array.every() function in PHP. I have come across the each() function in PHP, but it doesn't quite meet my requirements. ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

Executing a cross-site scripting (XSS) simulation within a MVC4 application on Visual Studio 201

Within my MVC 4 application, I am experimenting with simulating an XSS attack. The setup involves a button and a text box that simply outputs the entered value. However, when I input <script>alert('xss')</script> into the text box, an ...

Interfacing Contact Form Data from Vue Application to Magento Using API - A Step-by-Step Guide

Introduction A custom vue-component has been implemented on the application, serving as a contact form. This component is imported into the header component and enclosed within a modal container. The primary function of this contact form is to trigger an ...

Trouble with the Display of Divs in AngularJS

I have been attempting to toggle the visibility of a div element. The goal is to show a list of hospitals and, upon clicking on a hospital name, display corresponding information using AngularJS. I've noticed that if I remove 'ng-repeat="x in dat ...

Imported function encounters a non-function error

I'm encountering a puzzling reference/binding error that I can't seem to resolve: import React from 'react'; var { View, StyleSheet, Alert, AsyncStorage } = require('react-native'); import {Button} from 'react-native-el ...

The counter is failing to show the minimum amount of double numbers

In an attempt to track the fewest number of rolls needed to get a double in a game, I want the counter to update with a new lowest count if the player achieves an even lower number of doubles on their next try. count=0, doubles=0, lowest=10000000; fu ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

"Exploring the possibilities of integrating Typescript into Material-UI themes: A step-by

I'm experiencing some issues with Typescript pointing out missing properties in the palette section. Although adding //@ts-ignore resolves the problem temporarily, I would prefer to find a cleaner solution. As a newbie to Typescript, here is my attemp ...

How can we display the first letter of the last name and both initials in uppercase on the JavaScript console?

I'm a new student struggling with an exercise that requires writing multiple functions. The goal is to create a function that prompts the user for their first and last name, separates the names using a space, and then outputs specific initials in diff ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

NodeJS with Gulp Streams and Vinyl File Objects: Troubleshooting Incorrect Output Issue in NPM Package Wrapper

Mission My current project involves creating a Gulp wrapper for NPM Flat that can be seamlessly integrated into Gulp tasks. This initiative aims to benefit the Node community while also helping me achieve my objectives. You can access the repository here ...

Getting access to the DOM element in AngularJS can be achieved through various methods

I'm a newcomer to AngularJS and I have successfully set up basic routing in my app. However, I am now looking to enhance the interactivity of my home screen by incorporating a typewriter js script: const texts = ['123', '456', &ap ...

Incorporate this layout employing Java

Is there a way to achieve the following format in Java? Desired Output: 1 8 15 2 9 16 3 10 4 11 5 12 6 13 7 14 Java Code: int a = 1; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(a++); } System.out.println(""); } ...