cpeddie
cpeddie

Reputation: 799

testing for uninitialized array element not working

I'm trying to test if an array has the second dimension added. It it does I push the new record onto it, if it doesn't I add the second dimension then do the push. I've read in multiple places the way to test for the 2nd dimension being undefined, but it is not working for me. Here's the code:

if ( typeof missionData[numMissions][0] === 'undefined') {
    missionData[numMissions] = [];
    missionData[numMissions].push(missionRecords.record[index])
}
else {
    console.log('both array dimensions exist, pushing record');
    missionData[numMissions].push(missionRecords.record[index]);
}

When it executes I get the following error:

controller.js:710 Uncaught TypeError: Cannot read property '0' of undefined

Everything I've read tells me what I'm doing is correct, but obviously it is not. What am I missing?

Thanks.....

Upvotes: 1

Views: 24

Answers (2)

Mass C
Mass C

Reputation: 41

The issue is that you are trying to access the element at 0 position of an array that does not exists, so you get that error. And you can be more DRY as you are always going to push the missionRecords.record[index] anyway:

//If undefined you can just use the !(not) operator.
if (!missionData[numMissions]) {
    missionData[numMissions] = [];
}
missionData[numMissions].push(missionRecords.record[index]

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122018

missionData[numMissions] itself the array.

You just don't need to access the 0th element. Check the array is there or not.

if ( typeof missionData[numMissions] === 'undefined') {

That's all

if ( typeof missionData[numMissions] === 'undefined') {
    missionData[numMissions] = [];
    missionData[numMissions].push(missionRecords.record[index])
}
else {
    console.log('both array dimensions exist, pushing record');
    missionData[numMissions].push(missionRecords.record[index]);
}

Upvotes: 0

Related Questions