Constructing items within an array literal using a constructor method

I am attempting to create an object using my Person constructor. However, I am encountering issues when I try to initialize the object directly in the array using literal notation.

function Person(name, age) {
    this.name = name;
    this.age = age;
} 

var family = [
    [new Person("alice", 40)],
    [new Person("bob", 42)],
    [new Person("michelle", 8)],
    [new Person("timmy", 6)]
];

for (var person in family) {
    console.log(family[person].name);
}

Unfortunately, it only displays undefined four times.

To resolve this issue, I must utilize the following notation:

var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

Upon doing so, I successfully print out alice, bob, michelle, and timmy.

Can someone please point out what mistake I am making?

Answer №1

You can quickly set up your array of family members like this:

var familyMembers = [
     new FamilyMember("alice", 40),
     new FamilyMember("bob", 42),
     new FamilyMember("michelle", 8),
     new FamilyMember("timmy", 6)    
];

No need to wrap each FamilyMember in brackets.

Now you can easily iterate through the array elements with a loop like this:

for (var i=0; i<familyMembers.length; i++) {
    console.log(familyMembers[i].name);
}

I opted not to use for..in as it serves a different purpose:

The for..in statement loops over an object's enumerable properties in arbitrary order. You can execute statements for each property.

For more information on for...in, check out this link.

function FamilyMember (name, age) {
    this.name = name;
    this.age = age;
} 

var familyMembers = [
         new FamilyMember("alice", 40),
         new FamilyMember("bob", 42),
         new FamilyMember("michelle", 8),
         new FamilyMember("timmy", 6)    
    ];

for (var i=0; i<familyMembers.length; i++) {
    document.write(familyMembers[i].name);
    document.write("</br>");
}

Answer №2

Instead of creating a 2D array, it seems like you just need a regular array. To achieve this, simply use a standard for loop for iteration:

var friends = [
    new Person("bob", 35), //avoid using inner arrays
];

for (var j = 0; j < friends.length; j++) { 
    //display names
    console.log(friends[j].name);
}

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

Assistance required for posting Jquery files

Attempted to upload a file using jQuery with a hidden form and an Input element, triggering the file browser with jQuery. The changed input is then sent to a PHP server script. Encountered an issue where submitting the form with $("form1").submit(); worke ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...

Tips for creating a clickable popover within a window that remains open but can be closed with an outside click

Is there a way to ensure that my popover window remains clickable inside its own area without closing, but automatically closes when clicked outside of the window? This is the code I am currently using, which is triggered by a button click: if (response. ...

In R, extracting rows from mydataframe based on an array of values, even when the array and mydataframe have different lengths

I have two sets of data, gg and yy, with the following characteristics: > str(gg) num [1:1992] 128 130 132 185 186 187 188 189 190 191 ... > str(yy) 'data.frame': 2103 obs. of 2 variables: $ grp : num 128 130 132 185 186 187 188 189 ...

creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors. How can I achieve this correctly? Using "item.id" and "index.id" does not ...

Nested iteration using a for loop in Javascript

I am attempting to iterate through a large array of values and calculate the average of one of the values for each second. I seem to be having trouble getting this code to function correctly, and it appears that the issue lies within the nested while loop. ...

What distinguishes the pair of pointer assignments in the language of C?

After extensive research and experimenting with code, I am still puzzled by the following question: What is causing an error in case 1? Case 1: int arr[] = {0,4,7}; int *p = arr[0]; // pointing to the first element printf("%d", ++*p); // This leads to a ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

Incorporate a fresh attribute into each JSON object within a JavaScript array

Currently, my focus is on a react application where I am retrieving a JSON response from a specific route that consists of a collection of JSON objects. My objective now is to introduce a new field in each JSON object based on another field within the sam ...

When utilizing PHP Form Validation alongside Javascript, the validation process does not halt even if a

I have been grappling with creating a basic HTML form validation using Javascript After experimenting with various examples, I am still facing the issue of my index page loading upon clicking the button on the form. Despite including "return false" in wha ...

Tips for updating or refreshing a table in Rails using Actioncable

My Action Cable functionality is performing well, displaying an alert with the data content (although this alert appears on all pages). Here's the scenario: a user with the role of ADMIN can access a URL (http://localhost:3000/ventas/) that contains ...

I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration. One specific route on the backend returns an array of 'Candidates': exports.list = function (req, res, next) { const sort = req.query.sort || null ...

Express.js throws an error when trying to access req.session when it

I've searched through multiple posts on this topic, however, none were able to resolve my issue. Below is the code snippet from my server.js file: var express = require('express'); var app = express(); app.configure(function(){ app.set ...

What is the best way to enable my array to function properly when assigning non-consecutive numeric indexes using jQuery?

I have a dynamic XML file generated from a database that contains both an ID and a name for each item. It is structured as follows: <item> <id>1</id> <name>FirstName</name> </item> ... and so forth ... I am atte ...

Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present. Please choose a client from the opti ...

Nextjs attempting to access local storage without proper initialization

I'm currently working on a feature where I have a sidebar with two buttons, contact and profile. When a user clicks on either of them, the URL updates to: /?section=clickedItem, allowing the user to save the state and return to that specific page upon ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

Error: Attempting to access properties of an undefined object (specifically, the 'prototype' property) within a React application

I encountered an error while working on my React application: TypeError: Cannot read properties of undefined (reading 'prototype') (anonymous function) C:/Users/tatup/Desktop/GrowApp/frontend/node_modules/express/lib/response.js:42 39 | * @pub ...

Discovering documents using the outcome of a function in mongoose

Hey there, I have a scenario with two schemas known as user and driver, both containing latitude and longitude attributes. My goal is to search the database for nearby drivers based on the user's current location (latitude and longitude) using a custo ...

What steps are needed to enable the keyboard on a Otree application for mobile devices?

I previously utilized an Implicit Association Task (IAT) in an experiment conducted on computers. However, I now need to adapt this IAT for use on tablets or mobile devices. Here is how the IAT appears on a cellular device: https://i.stack.imgur.com/kNwo ...