JavaScript - Unusual behavior of Array_Push()

I am experiencing an unusual behavior with Array_Push(). When I add an array to a predefined array, the length of the array unexpectedly increases by two instead of one.

Below is the code snippet:

Example array:

Object {id: 2, firstName: "First name", lastName: "Last name", phones: Array[0], emails: Array[0]…}$$hashKey: "00A"address: "Street 3"city: "Washington "emails: Array[0]firstName: "First name"id: 2lastName: "Last name"notes: "No notes"phones: Array[0]__proto__: Object

JavaScript Code:

var contacts = [
        {
            id: 0,
            firstName: 'John',
            lastName: 'Doe',
            phones: [{'phone1': '222222222'}],
            emails: [{'email1': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="412439202c312d24012c20282d6f222e2c">[email protected]</a>'}],
            address: 'Some Streetz 2.',
            city: 'Las Vegas',
            notes: 'Napomena',
        },
        {
            id: 1,
            firstName: 'Mike',
            lastName: 'Smith',
            phones: [{'phone1':'111111'}],
            emails: [{'email1': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b0adb4b8a5b9b095b8b4bcb9fbb6bab8">[email protected]</a>'}],           
            address: '459 5th Av.',
            city: 'New York',
            notes: 'Napomena',
        }
    ];

Adding an array to the contacts array:

this.addContact = function (contact) {

        alert (contacts.length);//output is 2
        contact.id = contacts.length ++;//getting ID od new array
        console.log(contact);//
        contacts.push(contact);
                        alert ("++"+contacts.length);//output is 4

                console.log(contacts);

    };

Answer №1

contacts.length++ serves to increase the size of an array by one, essentially performing the same action as contacts.push(undefined). This operation ultimately results in adding another element to the array.

The correct choice is contact.id = contacts.length. If for some reason you needed to generate an ID that was "one more than the current length" (even though this isn't typically necessary), it would be properly expressed as contact.id = contacts.length + 1.

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 used for making an AJAX request

Currently, I am attempting to master the art of making an AJAX call using plain JavaScript with the goal of stepping away from JQuery for a specific project. However, I seem to be encountering a roadblock when it comes to xmlhttp.onreadystatechange. If a ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Locate the product of n numerals within a specified interval

Is there a way to determine the number of multiples for N unique numbers (provided as an array input) within the range of 1 to K, where 1 < K < 10⁸ and 3 ≤ N < 25? function findNumberOfMultiples(inputAr ...

What happens when 'grid' property is undefined in modal?

I encountered an issue with my modal where I wanted to display pre-selected rows, but kept getting a 'cannot read 'grid' of undefined' error. The UI Grids are defined within the modal, and I have declared two Grid APIs with different na ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

An effective method for cutting off text while preserving HTML styling using jQuery

Is there a way to truncate text using jQuery while preserving the HTML formatting? I attempted the code below, but it doesn't maintain the HTML tags. var truncate = function() { $('p.truncated').text(function(index, oldText) { if (old ...

The two CSS classes are styled with different border-color values, but only one is being applied correctly

My goal is to modify the border color of a textarea using jQuery. Previously, I achieved this by using .css("border-color","rgb(250,0,0)"), and it was working perfectly. However, I have now been advised against using CSS directly in JavaScript and told to ...

The Eigen array often gets mistaken for OpenGL

Encountered an unexpected error while working on this code snippet: Eigen::Array <GLfloat, NumVertices, 2> vertices; vertices(0, 0) = 0.90f; vertices(0, 1) = 0.90f; vertices(1, 0) = 0.90f; vertices(1, 1) = -0.90f; vertices(2, 0) = -0.90f; vertices(2, ...

Activate the selected image on click and deactivate all other images

Looking to use Javascript onclick to create an event where the clicked image is enabled and others are disabled. For instance, if there are 6 pictures, how can I achieve this: Clicking on any picture, let's say number 3, will enable that picture whil ...

There seems to be an overload of commas showing up in my array

I recently developed a program that captures user inputs to create an array and then reverses the array. However, I encountered an issue with the printing of values separated by commas as it is adding one extra comma. Below is the snippet of my code: #inc ...

Displaying a tableview of images converted from an array of base64 strings

I am facing an issue with binding images in base 64 format from an array to a table view. I attempted using the code snippet below to convert base 64 strings to image: UIImage *image = [UIImage imageWithData:[NSData dataFromBase64String:result]]; Howeve ...

Adjust the input and transition the UI slider

Currently, I am facing an issue with two sliders and inputs. When the number in the top slider is changed, the number and slide in the bottom block do not update accordingly. What steps should I take to address this? $(document).ready(function() { var $ ...

Allow-Origin-Control, handler.php for emails, and form validation script

I encountered a strange bug recently. There's been some issues with the HTML5 template I downloaded, specifically related to the contact form and MailHandler.php file. Despite having both files in the same directory, when inspecting element in Chrome, ...

Update web page content using JavaScript onClick

I'm trying to figure out how to refresh my page every time a door is clicked. Can anyone help me with where I should add window.location.reload(); in my code? Here's the link to my pen: https://codepen.io/tacodestroyer/pen/bROpeQ function open ...

What is the method for determining if a given point falls within a 3-dimensional cube?

I am currently seeking a method to determine whether a location is situated inside a rotated cube. To provide some context, I have access to the coordinates (x,y,z), rotation values (x,y,z), and dimensions (x,y,z). I am working with Javascript for this pr ...

Why is the JSfiddle tutorial not functioning properly in other environments, generating the error "Property 'clientHeight' cannot be read of null"?

I've been diving into a THREE.js tutorial to learn how to set up a basic scene and add animation keyframes triggered by scrolling. Everything worked smoothly in the fiddle, but when I tried to transfer it to my website, I encountered this persistent e ...

I often struggle with creating social media buttons using Material UI

https://i.sstatic.net/jmZKS.jpg https://i.sstatic.net/4RQwe.jpg Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

Issue with incorrect date being retrieved in MongoDB response from a node server

My date in mongodb is structured as follows: ISODate("2020-08-03T00:00:00.000+05:30"), However, after querying the date, it appears like this: 2020-08-02T18:30:00.000Z I am looking to get the correct date of 2020-08-03. What could I be doing wr ...