0

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

3 Answers 3

1

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

document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Glad to help you
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.