What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array.

Expected: Prior to invoking the learn() method, I anticipate receiving an array with random values on the console.log()

Actually: Instead, upon this console.log(), I am already seeing an array from the next line in the changeWeights() method

Code:

import {Injectable} from '@angular/core';
import {Letters} from "../constnants/letters";
import {Alphabet} from "../constnants/alphabet";
import {GeneralWeights} from "../constnants/weights";

@Injectable({
  providedIn: 'root'
})
export class LearningService {
  public theta: number = 0;
  letters = new Array<number[][]>();
  d: number = 0;
  weights: number[][] = [[]];

  constructor() {
    this.initTheta();

    this.initArrays();

    this.weights = this.generateWeights(7, 5);
    
    console.log('Expecting generated values here: ', this.weights);

    this.learn();
  }

  public learn(): void {

    for (let n = 0; n < Alphabet.ALPHABET.length; n++) {
      let counter;
      while (true) {
        counter = n;
        for (let i = n; i < Alphabet.ALPHABET.length; i++) {

          this.d = Alphabet.ALPHABET[i] === Alphabet.ALPHABET[n] ? 1 : 0;

          console.log("checking ", Alphabet.ALPHABET[i], ': ');
          const x = this.letters[i];
          const res: boolean = this.isRight(this.getSum(x));

          if ((i !== n  && res) || (i === n && !res)) {
            i--;
            this.changeWeights(x, res, this.d);

            console.log('');
          } else {
            GeneralWeights.WEIGHTS.push(this.weights);
            counter++;
          }
          if(counter === 33) {
            console.log(GeneralWeights.WEIGHTS);
            return;
          }
        }
      }
    }

  }

  comparisonSum(twoDimensionalArray: number[][], index: number): number {
    let sum = 0, i = 0, j = 0;
    twoDimensionalArray.forEach(array => {
      j = 0;
      array.forEach(item => {
        i = 0;
        sum += item * GeneralWeights.WEIGHTS[index][i][j];
        j++;
      })
      i++;
    })
    return sum;
  }

  generateWeights(rows: number, cols: number): number[][] {
    return Array.from({ length: rows }).map(() =>
      Array.from({ length: cols }).map(() => Math.random())
    );
  }

  public getSum(x: number[][]): number{
    let sum = 0;
    for (let i = 0; i < 7; i++){
      for (let j = 0; j < 5; j++){
        sum += x[i][j] * this.weights[i][j];
      }
    }
    console.log("sum = ", sum);
    return sum;
  }

  public isRight(sum: number): boolean {
    return sum >= this.theta;
  }

  private changeWeights(x: number[][], y: boolean, d: number): void {
    console.log("New weights: ");
    let ni = 2.5;
    let e = d - (y ? 1 : 0);

    for (let i = 0; i < 7; i++) {
      for (let j = 0; j < 5; j++) {
        // this.weights[i][j] += ni * e * x[i][j];
        this.weights[i][j] = 0;

      }
    }
    console.log(this.weights);
  }

  private initTheta(): void {
    this.theta = Math.random() * 2 -1;
    console.log('θ = ', this.theta);
    console.log('');
  }

  private initArrays(): void {
    for (let letters of Letters.LETTERS) {
      this.letters.push(letters)
    }
  }

}

Answer №1

The issue lies in the fact that the browser console automatically updates the array when it undergoes changes from the code. This behavior persists unless you create a clone of it and sever the reference to the original.

To properly log the values, try using console.log() as shown below:

console.log('When using this log, I anticipate seeing the generated values: ', JSON.parse(JSON.stringify(this.weights)));

By following this approach, you will be able to observe the initial state before executing the learn() function.

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

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

It appears that the Angular 2 HTTP header is being produced or transmitted erroneously

Trying to send a request to my backend that uses HTTP Basic authentication for testing purposes. username: user password: password The correct header should be: Authorization: Basic dXNlcjpwYXNzd29yZA== Request tested with this header in Chrome Advance ...

Using Ajax and PHP to upload an image

I'm looking to implement an image upload feature triggered by a button click with the id of #myid.save. Below is the code I have so far: HTML Code: <canvas id="cnv" width="500" height="100"></canvas> <input id="myid_save" type="submit ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

Exploring VueJS reactivity: Updating an array with new data

I am struggling to understand why certain methods of changing data seem to work while others do not. In an attempt to clarify, I experimented with the following example: watch: { '$store.state.linedata': function() {this.redraw()} } ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Remove any overlapping datetime values from a JavaScript array of objects

Is there a way to efficiently remove any overlaps between the start and end times (moment.js) in a given array of objects? [{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")}, { start: moment("2019-03-23T14:40:00.000"), e ...

The functionality of `req.isAuthenticated()` is never true when using PassportJs with a combination of nodeJS and dynam

I am entering the world of web programming and tasked with creating an Instagram-like platform for my school. The frontend is built in ReactJS and now it's time to develop a server in nodeJS, utilizing passport for authentication and dynamoDb for data ...

What is the process for transforming pagination numbers into Arabic numerals?

When working with pagination in my project, I have utilized both ant design and material ui. However, I encountered a problem when attempting to change the default Latin numbers to Arabic numbers. Despite trying ant design localization, I was unable to aff ...

New functionality introduced in JavaScript ES6: Sets

I am currently using a Set data structure to store unique primitive values, but I am facing an issue when trying to add unique objects based on their property values. Below is an example of my code: "use strict" var set = new Set(); var student1 = { ...

Learn how to set expectations on the object returned from a spied method, Jasmine

I am currently faced with setting an expectation regarding the number of times a specific function called "upsertDocument" is executed. This function is part of a DocumentClient object within a getClient method in production. Here's how it looks: cli ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Implementing a universal timer for tmi.js and discord.js integration

I am currently working on a Discord bot that monitors multiple Twitch chats for commands and executes them on Discord using tmi.js and discord.js. Everything is functioning as expected, but I am facing an issue with implementing a global cooldown on the ...

The suspense fallback function seems to be missing in NextJS 13

I'm in the process of creating an application to demonstrate the functionality of Suspense in Nextjs 13. However, I'm encountering an issue where the Suspense fallback is not appearing during loading. Below is the code for page.js import React, ...

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

Creating a standalone script using npm JS package for exporting

I'm currently utilizing the npm package manager in my latest project. Within my package.json file, I have a dependency specified: "dependencies": { "litepicker": "^2.0.11" }, The dependency is on litepicker, which i ...