The 2D array created using a for loop in JavaScript is getting replaced by the value in the last iteration

Looking to create a pseudo-random sequence generator similar to the Linear Feedback Shift Register, but in JavaScript due to familiarity with the language, and using HTML for the GUI interface. The user will input an initial value to receive a schematic diagram and the generated pseudo-random sequence.

var UserInput = document.getElementById('input');
var Output = document.getElementById('output');

// Array of objects containing circuit images and tap configurations required for shift registers
   
function generateSequence(){
    var data = [
        {
            image:"pic/2bit.png",
            tap:[0,1]
        },
        ...
        ...
        // List of circuit configurations
    ];

    var first = UserInput.value.split("");
    for (k=0; k<first.length; k++) {
       first[k] = +first[k]; 
    }

    var bit = first.length - 2;
    var matrix = [first];
    var t = 0;
    var between;
    var z;

    for (i=1; i<Math.pow(2, bit+2)-1; i++){
        for (j=0; j<data[bit].tap.length; j++){
            z = data[bit].tap[j];
            t = t ^ matrix[i-1][z];
        } 

        between = matrix[i-1];
        console.log(between);
        between.unshift(t);
        between.pop();
        matrix[i] = between;
        t = 0; 
    }   
console.log(matrix);
}

You can access the HTML code here.

The issue lies in that while console.log(between); displays the last generated row correctly, console.log(matrix) overwrites all rows by the last one. Expected output should be:

101
010
001
100
110
111
011

Instead, it currently shows:

011
011
011 ...

The solution is still incomplete and does not display in HTML. Additional work is needed to extract the pseudo-random sequence from the final matrix column.

Answer №1

I came to the realization that the variable "between" actually refers to the same array as var matrix[i-1], rather than creating a completely new and independent array.

between = matrix[i-1];

Therefore, if you want to store only the values of matrix[i-1] without creating a reference, you can achieve this by using:

between = JSON.parse(JSON.stringify(matrix[i-1]));

In JavaScript, when you make a copy of an array in a variable, it automatically creates a reference to that array. There are several ways to avoid this behavior, and you can explore various examples here.

Answer №2

It's puzzling to me, but I've managed to find a solution (I'll delve deeper into it when I have some free time).

for (i=1; i<Math.pow(2, bit+2)-1; i++){     //Adjustment made here with +2 since I had -2 previously. The loop starts from 1 and ends at <2^n-1 because the first matrix array is already there
    for (j=0; j<data[bit].tap.length; j++){
        z = data[bit].tap[j];
        t = t ^ matrix[i-1][z];
    }      // Thet generates "t" by XOR-ing all taps together. For example, if the user input was 101 and tap would be [0,2], then t would be 1xor1=0
    between = matrix[i-1];
    console.log(between);
    between.unshift(t);
    between.pop();
    // MODIFICATION
    var between_string = between;
    matrix[i] = between_string.join(); // Convert it into a string
    matrix[i] = matrix[i].split(','); // Revert it back to an array to maintain functioning in the above for loop.
   // END MODIFICATION

    t=0;    // This step involves "shifting registers" or moving t to the front of the last row generated while removing its last digit, thereby creating a new row 
}   

Now, when you display this in the console, you'll see a bidimentional array. However, it may appear bizarre sometimes (in my console) showing integers and other times mixed with strings (adhering to the original values of 'between').

Edit: Initially, I tested using only "101" as input.

Second edit: Well, I must admit, the reason it outputs [1, "0", "0"] (for instance) is due to the split(',') function transforming "1,0,0" (only two numbers preceded by commas). Haha. Apologies.

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

Repurposing components like custom text inputs, spans, and more in ASP.NET MVC using Razor

Our team is currently working on a website project where we keep re-using components repeatedly. One particular instance involves a span that functions as a warning light. It's accompanied by some C# code with properties for color and text, Javascript ...

Guide on displaying a Custom 2D shape on both sides using three.js

As a beginner to three.js and 3D programming in general, I recently used three.js to draw a sector. However, I am facing an issue where I can only see the object in one direction but not in the opposite direction. It appears that the same phenomenon is h ...

What are alternative methods for creating a two-column form layout that do not involve the use of

When generating the html form, I am looping through the form variables as shown below: {% for field in form %} {{ LABEL }}{{ INPUT FIELD }} The labels and fields are going through a loop. A simple one-column layout can be generated using: {% for field ...

Create a variety of exam papers using text documents

Looking to create a simple Java program, but unsure of where to start. How can I go about developing a flow or pseudocode before diving into the actual programming process? I have two text files filled with questions - one holds 60 questions and the other ...

parallax scrolling can be a bit bumpy

While working on a website, I've incorporated a slight parallax effect that is functioning almost perfectly. However, I've noticed that the foreground divs tend to jump a little when scrolling down the page. At the top of the page, there is a di ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...

The catch block appears to be malfunctioning when attempting to delete an object with an invalid ObjectId

Everything seems to be functioning correctly in the try block, and I'm receiving the expected response as intended. However, when attempting to delete an object with an invalid ID, the catch block is not behaving as expected. Instead of receiving a JS ...

What is the best way to set a default selected option in an ng-multiselect-dropdown using Angular?

Here, I am retrieving data from the database and storing it in an events array. The data in this events array is displayed on the book-ticket.component.html using ng-multiselect-dropdown. Upon selecting an option, the corresponding data is stored in this.e ...

Could someone please provide clarification on this specific JavaScript syntax? I am unsure about the usage of `const {

Although I am not very familiar with javascript, I have come across this syntax and I would greatly appreciate it if someone could help me understand it! Regarding Node.js const { check, validationResult } = require('express-validator/check') ...

Identifying the web browser by utilizing the UserAgent detection method

How can I determine if the current browser is Chrome using TypeScript/JavaScript? I previously used the following method: var isChrome = !!(<any>window).chrome && !!(<any>window).chrome.webstore; However, this doesn't work anymo ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

Having trouble getting the jQuery validate function to work properly with a select element

I have successfully implemented a validate function for my input fields : $.tools.validator.fn("#password", function(input, value) { return value!='Password' ? true : { en: "Please complete this mandatory field" }; }); $("# ...

Validation of form groups in Angular 2 using template-driven approach

I am seeking guidance on how to handle form validation in Angular 2 template-driven forms. I have set up a form and I want to display a warning if any input within a group is invalid. For example, consider the following form structure: <form class="fo ...

Click on a table cell in Vue to display its corresponding data in a modal

I have successfully implemented a modal in my Vue component that works well with static text inside it, confirming its functionality. However, when attempting to pass data from the table cell that is being clicked into the modal, I encountered an error st ...

Unable to retrieve specific elements using this.$refs in Vue.js

I've encountered a peculiar issue. I'm trying to access certain elements within the created() hook, but I seem to be running into some trouble specifically with the refs object: created() { console.log(this.$refs) } // outpu ...

In my current project using React, I am working on creating a user interface that will feature three buttons, each corresponding to a different collection. When a button is clicked

I have been working on importing an array of objects using an axios get request. My goal is to assign a specific value to each of the three buttons based on the objects in the array. I attempted to use .map to iterate over the array and generate buttons ...

React - Trouble rendering JSON file

I am working on a row of react-icons. Once clicked, the icons should display content from a static .JSON file. I am trying to achieve the following functionalities: Change color when clicked Switch between the static .JSON content when clicked. I at ...

Filtering an array of nested objects in JavaScript: A step-by-step guide

Let's say I have an array structured like this: const arr = [ { id: '123', book: {isNew: true} }, { id: '123', book: {isNew: false} }, { id: '123', book: {isNew: false} }, { id: & ...

Executing JavaScript code from a web browser in Node.js

I have created a simple JavaScript code in AngularJS and I would like to be able to execute it in both Node.js and the browser depending on the situation. While I am aware of the tools like browserify or lobrow that allow running Node.js code in the brows ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...