bobhand
bobhand

Reputation: 19

pushing variables to array returns undefined

SOLVED, Thank you! I needed to specify the index.

I am trying to push a set of variables into an array from user input. Without using push it is working fine;

var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
document.write(appointmentArr.start);
document.write(appointmentArr.end);

however, when I try to push the variables it returns undefined;

var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr.start);
document.write(appointmentArr.end);

Can anyone explain why this is happening? As far as I am aware I need to use push because I eventually want to create a new, populated index number every time the user inputs data, so any help is greatly appreciated. Thanks in advance

Upvotes: 0

Views: 1074

Answers (3)

Isitea
Isitea

Reputation: 751

You re-assigned your variable as Object.

var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};

This code overwrite appointmentArr from Array [] to Object { start:inputStart, end:inputEnd }

And in the second code:

var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});

You modify appointmentArr from Array [] to Array [ {start:inputStart, end:inputEnd} ].

So, following code will work as you want.

document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

Upvotes: 0

Pajri Aprilio
Pajri Aprilio

Reputation: 322

You are accessing array. So, the document.write part should be like this

document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

Upvotes: 1

Sravan
Sravan

Reputation: 18657

Since appointmentArr is an array, you should fisrt take appointmentArr[0] to access the first element of the array.

After you push the value, the appointmentArr becomes, [{start:inputStart, end:inputEnd}]

Since, it is an array you cannot access object keys directly, you have to take specific index element and then can access them using appointmentArr[index]

    var inputStart = 'inputStart';
    var inputEnd = 'inputEnd';
    var appointmentArr = [];
    appointmentArr.push({start:inputStart, end:inputEnd});
    document.write(appointmentArr[0].start + ' ');
    document.write(appointmentArr[0].end);

Please run the above snippet

Upvotes: 1

Related Questions