Whenever I execute my code, the browser consistently crashes

Here is the code I have been working on:

var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg", "image7.jpg", "image8.jpg"];
var objects = [];
var geometry;

while(objects.length < images.length) {

        var imagesIndex = 0;
        var object = [

            texture1 = textureLoader.load( "data/"+ images[imagesIndex] ),
            material1 = new THREE.MeshBasicMaterial( { map: texture1 } ),
            objectMesh = new THREE.Mesh( geometry, material1 ),
            location3d = new THREE.Vector3( Math.random()* 500-250, Math.random()* 500-250, Math.random()* 500+120 )

        ];  

        var overlapping = false;
        for (var j = 0; j < objects.length; j++) {
            var projectCubeLoc = objects[j][0][3];

The line

var otherCubesLoc = projectCubeLoc[j];
leads to an error.

            var otherCubesLoc = projectCubeLoc[j];
            var distance = projectCubeLoc.distanceTo( otherCubesLoc );
            console.log(distance);

            if (distance < 150) {
                overlapping = true;
                break;
            };
        };

I moved the statement outside of the for-loop because if no overlap occurs, at least one object will be added to the array.

        if (!overlapping) {
            objects.push(object);
            imagesIndex++;
        };
     };

However, now I am encountering a TypeError: Cannot read property '0' of undefined.

When running this code in the browser, it crashes without displaying any error messages. The browser just quits unexpectedly. I suspect there may be an issue with the while loop, but I can't pinpoint the exact problem.

Any assistance or suggestions would be highly appreciated!

If you require more code snippets or would like to see a JSFiddle example, please let me know :)

Answer №1

The objects array is not being assigned any values.

Your for loop never reaches the objects.push function call in your code.

Since you initialize the array as empty, when it reaches the for loop with j == 0 and objects.length == 0, the loop does not execute.

Answer №2

Unity3d may be the platform you're utilizing, as I encountered a similar issue while attempting to run C# code. Your problem lies in declaring a variable within a loop - upon each update, the variable is continually reset to zero, resulting in a mesh.

Answer №3

  1. When the loop
    while(objects.length < images.length)
    begins, there is an empty array which passes initially because the length of objects is less than that of the images array.
  2. As you progress, a new variable object is declared with the intention of being added to the objects array. However, the for loop
    for (var j = 0; j < objects.length; j++)
    starts using the length of objects, which has not been initialized yet in the function. Therefore, it will never enter the loop.
  3. The statement
    if (!overlapping) {objects.push(object); imagesIndex++;}
    cannot be reached because the loop does not start.

No values are pushed into the objects array, leading back to the initial point and causing an infinite loop in your function, ultimately crashing the browser.

Description: As the function begins execution, the length of 'objects' is 0 which is less than the image array's length, creating a valid condition. However, during the inner loop execution, the length of 'objects' is still zero as no value has been added to the object. This results in the for loop not executing as 'objects.length' remains 0. The cycle continues infinitely since no values were added to 'objects' before the loop. I hope this clarifies any confusion.

Answer №4

let pictures = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg", "image7.jpg", "image8.jpg"];
let items = [];

shape = new THREE.BoxGeometry( 100, 100, 100,10,10 );

while(items.length < pictures.length) {

    let picIndex = 0;

    let item = {};
    item.texture = textureLoader.load( "data/"+ pictures[picIndex] );
    item.material = new THREE.MeshBasicMaterial( { map: item.texture } );
    item.objectMesh = new THREE.Mesh( shape, item.material );
    item.coordinates = new THREE.Vector3( Math.random()* 500-250, Math.random()* 500-250, Math.random()* 500+120 );

    let overlap = false;
    for (let k = 0; k < items.length; k++) {
        let cubeLoc = items[k].coordinates;
        let dist = cubeLoc.distanceTo( item.coordinates );

        if (dist < 150) {
            overlap = true;
            break;
        };
    };

    if (!overlap) {
        items.push(item);
        picIndex++;
        item.objectMesh.position = item.coordinates;
        console.log(item.coordinates);
        scene.add(item.objectMesh);
    };
};

console.log(items);

i utilized a new object called "item" to simplify accessing data from the array of objects without encountering any issues. The modification works perfectly now ;) A big thank you to @Asad Jamil for all the assistance. Hopefully, this can benefit others in the future :)

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

Prevent reloading the page when adding a flash element using JavaScript (jQuery)

Here is the function I am working with: function onVideo(vchat, idUser){ $('#videollamada').html('<div class="videollamada">'+ '<div align="right">'+ ...

Unable to dismiss message in Django

I'm a beginner in Django and I recently followed a tutorial to add message alerts to my code. The alerts are displaying correctly, but unfortunately, I am having trouble closing them using the 'x' button. https://i.stack.imgur.com/BQS1S.png ...

JavaScript issue: "Error: Uncaught (in promise) SyntaxError: Unexpected end of input"

Encountering the following error message: Uncaught (in promise) SyntaxError: Unexpected end of input when attempting to post references to my specific express server. Can anyone here offer assistance? function create() { event.preventDefault() fi ...

Switching from Vue's Options API to Composition API is like transforming your code from

My goal is to transition the code below from using the options API to the composition API in Vue while utilizing Typescript. data() { return { items: [ 'Car', 'Truck', 'Bike', 'Ca ...

Both of the radio buttons in Material-UI have been selected

I have a unique document that showcases an implementation of RadioGroup, FormControlLabel, and FormControl. Take a look at the code snippet below for reference. import React from 'react'; import PropTypes from 'prop-types'; import Radio ...

Is there a seamless way to effortlessly upload massive files to s3 through an adminjs dashboard without encountering any glitches?

Attempting to upload large files (40mbs+) to s3 using the @adminjs\upload feature on the adminJS dashboard. While testing locally, most files are successfully uploaded but it takes a considerable amount of time. However, when attempting this on the AW ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Replace the current CSS styles of a pre-installed package

I recently added a package for a type writer effect, but I'm having trouble with it not overriding the CSS styles I've set in the component. Here's an example of what I have: <template> <v-row class="hero" align-content= ...

Creating a stylish gradient text color with Material-UI's <Typography /> component

Is there a way to apply a gradient font color to a <Typography /> component? I've attempted the following: const CustomColor = withStyles({ root: { fontColor: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", }, })(T ...

Is there a way to trigger an Angular $scope function from a hyperlink in the current or a new tab using a right

Here is the HTML code I am working with: <a href="" ng-click='redirectToEntity("B-",obj.id")'>Click me and Process function and then redirect</a> While this code successfully processes the function and redirects to the desired page ...

Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text name[one][1][two][45][text] Through this pattern, I am able to extract the number "45" /(.*?)rows\]\[([0-9]*)(.*)/; Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and re ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Explore numerous databases using mongoosastic

Currently in my Node.js application, I am utilizing Mongoosastic to fetch data from ElasticSearch : Article.search({ "match_all": {} }, function (err, results) { console.log(results.hits.hits); Post.search({ "match_all": {} }, function (err, r ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Looking to access the layout details of an HTML element similar to what can be done in Firefox's debugger tool?

I am facing a challenge with a aspx.net grid control where I need to extract the first row's information and copy it into another table using JavaScript. To achieve this, I am attempting to calculate the width of each cell in the first row by accessin ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

Utilizing turbolinks enables the page to be reloaded upon form submission

Currently, I have implemented turbolinks in my Rails application. However, every time I submit a form, the page reloads and the form is submitted. Is there a way to prevent the page from reloading and also submit the form seamlessly? ...

The dynamically generated table will only show the most recently added data

Currently, I am delving into the world of JavaScript to tackle an interesting challenge. Here's the scenario: I have a dropdown list populated with stream names derived from an array. Whenever a selection in this array changes using `onchange()`, I wa ...

JavaScript: Invoking a nested function within a namespace

script1.js var MyNamespace = {}; MyNamespace.addNewFunction = function(a,b,c) { function doSomething() { // Perform some action here } } script2.js MyNamespace.addNewFunction.doSomething() ?? I’m a bit unsure on how to access the content ...

Ways to forward a parameter to a different web address?

Is there a way to properly redirect a parameter such as http://example.com/?link=https://google.com to its destination at ? ...