What issues are there with JavaScript?

I encountered an issue with my JavaScript code where it is not producing the expected result.

var arr = new Array();

var firstobj = {
   cta: 0,
   ccc: 0,
   crc: 0
}
for (var ta = 1; ta <= 10; ta++) {
    arr[ta] = firstobj;
}

arr[6].cta = 1;
console.log(arr);

Despite only changing the cta value of the 6th element, it seems to change for all elements in the array.

Expected:

[{cta:0, ccc:0, crc:0}, ..., {cta:1, ccc:0, crc:0}, {cta:0, ccc:0, crc:0}, ...]
//                                ^ 6th element

Actual:

[{cta:1, ccc:0, crc:0, ...] // All have 1

Answer №1

In JavaScript, objects are assigned by reference (although JavaScript doesn't technically use pointers, the concept is similar to how pointers work in other languages). This means that when you fill an array with elements, each element contains a reference to the same object. As a result, any changes made to that object will be reflected everywhere because there is only one object being modified.

If you want to initialize an array with separate objects, you need to create new objects or clone existing ones and assign them to each element of the array individually.

Here's an example of how you can achieve this:

var myArray = [];
var obj;
// Remember, arrays in JavaScript start from index 0.
for (var i = 0; i < 10; i++) {
  // Create a new object for each item in the array
  obj = {cta: 0, ccc: 0, crc: 0};
  myArray[i] = obj;
} 

myArray[6].cta = 1;
document.write(JSON.stringify(myArray));

Answer №2

you have linked the same object reference to all elements in the array

try creating a new object for each element using Object.create

for (var index = 1; index <= 10; index++) 
{
    arr[index] = Object.create(newobj);
}

Answer №3

Instead of saving the same firstobj to your array and having it saved by reference, my recommendation is to create a new object for each element in the array. This way, when you make changes to one object, it won't affect the others.

var arr = new Array();

for (var ta = 1; ta <=  10; ta++) {
  arr [ta] = { cta:0,
               ccc:0,
               crc:0
            };
}

arr[6].cta=1;
console.log(arr);

Answer №4

It is important to note that only the 6th element's cta value should be 1, however, any changes made to one element affects all elements.

All elements within your array (except for the element at index zero, which is undefined in this scenario) reference the same object. This means that altering a property in one element will impact all other elements as well.

Answer №5

Every item in the array points to a single object. Thus, any modifications made to the object will be seen across all elements.

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

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

When using express, the response.sendFile() function is causing an Uncaught SyntaxError with the error message: Unexpected token <

Currently, I'm utilizing react-router with browserHistory. There is a specific function in my code that is meant to send the Index.html file since the routing is handled client-side with react-router. However, there seems to be an issue where the serv ...

Implementing conditional validation in Formik on cancel button click in a React application

When defocusing from the field without entering any data, a validation error occurs. Similarly, if you click on the submit button without giving a value, a validation error is triggered - this behavior is expected. However, how can we prevent the validat ...

Using Vue JS to handle image upload with "PROP MUTATING"

Apologies for any language barriers or inaccuracies in my English. I have a single component designed specifically for image uploads. It is currently being utilized in two forms: an add form and an edit form. In the edit modal, the Image URL is passed as ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

How to retrieve the filename from a URL using Node.js

In my Node.js script, I have the following type of link: 148414929_307508464041827_8013797938118488137_n.mp4.m4a?_nc_ht=scontent-mxp1-1.cdninstagram.com&_nc_ohc=_--i1eVUUXoAX9lJQ-u&ccb=7-4&oe=60835C8D&oh=61973532a48cb4fb62ac6711e7eba82f& ...

Lag in responsiveness of iOS devices when using html5 applications

My HTML5 video app includes a combination of video, a JavaScript swipable playlist, and other animated overlays. When using the app on iOS, the performance of playlist swiping and overlay animations is great upon initial load. However, after playing a vid ...

Issue with custom leaflet divIcon not maintaining fixed marker position during zoom levels

After creating a custom marker for leaflet maps, I noticed that it shifts position drastically when zooming in and out of the map. Despite trying to adjust anchor points and positions, the issue persists. I have provided the code below in hopes that someon ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

Tips for calculating the total of a virtual column through child associations in Sequelize

I have a network of 3 interconnected objects (A, B, and C). There can be multiple Bs associated with A, and multiple Cs associated with each B. For instance: A └───B │ └───C │ └───C └───B └───C Object ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

I'm curious about the meaning of "type" within a JSON object and how I can properly deserialize it into my model

After making an API call, I received the following object: [ { "$type": "foo.Api.bar.Entities.foo, foo.Api.bar.Entities", "id": "a2", "displayName": "A2", "statusSeverity": "Good", "statusSeverityDescription": " ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

When trying to import the "firebase/app" module, an error occurred stating that the default condition should be the last one to be considered

Greetings! I am diving into the world of webpack and firebase. Every time I use: import { initializeApp } from "firebase/app"; I encounter this error message: https://i.sstatic.net/tvuxZ.png Here is my file structure: https://i.sstatic.net/406o ...

What is the best way to integrate a Ruby object into JavaScript?

I'm attempting to integrate Ruby into the JS.erb file, where I need access to the @user object and its relationships. Instead of converting to a JSON object, I prefer the ERB to precompile on the server-side. My goal is to iterate in the JS file rat ...

Error: Unable to access attribute 'item_name' as it is not defined

I'm new to React.js and I'm attempting to build a todo app. The main feature is a text input field where users can add items to their list. When I run "npm start," the app works perfectly and displays the expected output on my designated port. Ho ...

What is the reason for being able to access `$scope` and `this` using the controller as syntax?

Creating an Angular controller with the controller as syntax: <body ng-controller="ctrl as myCtrl"> <p>Accessed via scope resolution: {{ foo }} </p> <p>Accessed via controller resolution: {{ myCtrl.foo }}</p> </body> ...

Utilize Autocomplete component from Material UI to sift through distinct option values

Looking to implement unique options in the dropdown menu of an Autocomplete component from Material UI based on a specific property within a list of objects. The current issue is that duplicate values are appearing in the dropdown, like ['Color1&apos ...

Ways to dynamically refresh a Vue component when data is updated without the need to manually reload the

After fetching data using axios, I noticed that my Vue component doesn't update automatically after a click event or when the data changes. As a workaround, I have to refresh the page to see the updated data. Is there a simple solution to this issue? ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...