Reputation: 2924
I need to use an array of emails whose each record should point to several attributes like To
, From
, and Subject
. I did something like this:
var emailAttr = new Array("to","from","subject");
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2"; // This line gives exception that emails[1] is undefined
What am i missing and how can i make it work so that I can access elements like emails[i].to
?
Upvotes: 0
Views: 1863
Reputation: 4360
You have to create an array which consists of objects.
So instead of these lines
var emails = new Array(emailAttr);
emails[0].to = "abc1";
emails[1].to = "abc2";
you can simply write this:
var emails = [{
to: "abc1"
}, {
to: "abc2"
}];
Upvotes: 0
Reputation: 4141
You should make the email an object and push those into an emails array:
// Create emails array
var emails = [];
// Create an email object
var emailObj = {
to: '[email protected]',
from: '[email protected]',
subject: 'Hello there'
};
// Add the email to the emails array
emails.push(emailObj);
// Will console log "Hello there"
console.log(emails[0].subject);
Upvotes: 1
Reputation: 943981
var emailAttr = new Array("to","from","subject");
This creates a new array with the values:
0: "to"
1: "from"
2: "subject"
Then
var emails = new Array(emailAttr);
This creates a new array consisting of one value:
0: The array you created in the previous line
Then this:
emails[0].to = "abc1";
adds a new property to the first array:
0: "to"
1: "from"
2: "subject"
to: "abc1"
and then this:
emails[1].to = "abc2";
… tries to do the same to the second item in the emails
array, but you haven't assigned an array there so you are trying to set a property on the undefined
object which isn't allowed and you get an error.
You probably want to create an array (for your ordered list of email objects) of objects (not arrays, use objects for named values, use arrays for numerically indexed, ordered values), and you need to create a new object for each member.
var emails = [];
emails.push({
to: "abc1",
from: "...",
subject: "..."
});
You can then repeat that to add any many items as you like.
You can edit items in it (but only ones you have already created) using your original syntax:
emails[0].to = "abc1";
NB: Best practise is to use the []
and {}
literals to create new arrays and objects, not the constructor functions Array()
and Object()
.
Upvotes: 1
Reputation: 360762
You first have to define what the child object is. When you write emails[1].to
, you're already trying to access that sub object before it's been defined.
Change it to:
emails = []; // create the main array
emails[0] = {to: 'abc1'}; // define an object and assign it to the main array
emails[1] = {to: 'abc2'};
Upvotes: 0