Contrasting assign and modify operations on arrays

After spending 2 days searching for a bug in my angular2 project's service.ts file, I finally found it and fixed it. However, I'm still trying to understand why the working code behaves differently from the bugged one, as they appear identical to me.

Here is the bugged code snippet:

for (let i = 0; i < quantita; i++) {
      this.a.p[inizio + i] = target;
    }

And here is the working code snippet:

this.a.p = this.a.p.map((giorno, index) => {
      if (index >= inizio && index < inizio + quantita) {
        return target;
      } else {
        return giorno;
      }
    });

In this code, "this.a" represents an array variable. The bug caused the changes to affect not just the selected object of the array, but also another one unintentionally. Despite debugging extensively and confirming that "this.a" was the correct instance and the code was only called once, the issue persisted.

I believe I've provided all pertinent information about the problem, but please let me know if more details are needed.

Answer №1

Storing an array in a variable means holding a reference to that array. Any changes made to the values in the array will be reflected in all references to it:

let a = [1, 2, 3];
let b = a; // same array stored in a different variable
for(let i =0;i< a.length;i++) a[i] = a[i] *2;

console.log(a); // [2;3;6]
console.log(b); // [2;3;6]

Using map creates a new array with the modified values from the mapping operation:

let a = [1, 2, 3];
let b = a;
a = a.map(n => n * 2) // new array assigned to a, b retains original array

console.log(a); // [2;3;6]
console.log(b); // [1;2;3]

An alternative is to create a new array and push values into it without modifying the original array using a for loop (although using map is recommended):

let a = [1, 2, 3];
let b = a; // same array in a different variable

let tmp = []
for(let i =0;i< a.length;i++) tmp.push(a[i] *2);
a = tmp;

console.log(a); // [2;3;6]
console.log(b); // [1;2;3]

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

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Enhance your data presentation with Angular Material tables featuring multiple sources

I am currently facing an issue with my table that is being used to display multiple sets of data. The problem I'm encountering is that while the data is showing up correctly, the paginator and sort functions are not working as intended. The sorting ...

How to turn off code splitting (chunks) in Vue.js and Vite.js

Is there a way to turn off chunking in Vue.js and Vite.js when building a project using Rollup.js? I attempted the following approach, but it did not work for me: export default defineConfig({ build: { rollupOptions: { output: { ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

The Next.js build encountered an error - unable to locate function in next/script module

While constructing a CMS using next.js, one of the key components is media management through Cloudinary. The integration of the Cloudinary Media Library widget was successful during development using next/script. However, an error has now emerged that pre ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

JavaScript and PHP are successfully displaying a success message despite the data not being saved to the database

I recently added a new feature to my website where users can submit a form using Javascript without having to reload or refresh the page. This allows for a seamless experience and displays success messages instantly. However, being a newcomer to Javascript ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

Displaying grouped arrays efficiently in Angular

I have received data from an API in the form of an array with objects structured like so: [ {"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1}, ...

What is the correct way to define the field name in the update() function of Mongoose?

When attempting to update every field contained in the dataToChange object, I encountered a problem where the update() method does not take the key name from the outside. Instead, it looks for a "key" field within the database's object. How can I work ...

What is the best method for sending XML data to a URL using JavaScript within an Adobe AIR application?

I am currently developing an application that involves downloading an XML string from a URL and then posting it to another URL. I have managed to successfully download the XML string and can manipulate it using alerts, however, I am struggling with posting ...

Extracting Object Properties in JavaScript with React

Code: const [obj, setObj] = useState(() => ({ a: valueA, b: valueB, get values() { if (!this.a || !this.b) { return []; } // code... } return [this.a, this.b] }, })); Values update: useEf ...

How to connect an external module to NuxtJS using Vue.js

Attempting to incorporate a widget/plugin/extension system into my existing web UI built with NuxtJS. Within the pages/view.vue single-file component, I aim to establish the extension system by dynamically loading components indicated through query paramet ...

How should elements be properly inserted into injected HTML code?

We are currently phasing out our custom forms in React on the website, and transitioning to Microsoft Dynamics 365 generated forms. These new forms are injected through a React placeholder component created by a script that loads the js bundle and inserts ...

You cannot call this expression. The data type 'Boolean' does not have any callable signatures

As I delve into learning a new set of technologies, encountering new errors is inevitable. However, there is one particular type of error that keeps cropping up, making me question if I am approaching things correctly. For instance, I consistently face t ...

Create random animations with the click of a button using Vue.js

I have three different lottie player json animation files - congratulations1.json, congratulations2.json and congratulations3.json. Each animation file is configured as follows: congratulations1: <lottie-player v-if="showPlayer1" ...

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...