Skip to content Skip to sidebar Skip to footer

Javascript - "variable Undefined" In One Part Of Loop, Working In A Different Part

Using the following code, I'm getting this error RewardPurchases.PurchasesArray[i].Student_Name is undefined: $('button#random').click( function() { var Num = Math.floor(Math.r

Solution 1:

Using for .. in isn't the greatest practice in situations like these. It does a deep dredge of ALL object properties, including functions belonging to the prototype.

The reason why only $('#display').text(... causes you issues is that you try to use a property of a property RewardPurchases.PurchasesArray[i]. Elsewhere, you use it by itself, which won't fail, it will just silently return undefined in those cases. (a.k.a., 'params': {'student': RewardPurchases.PurchasesArray[i].Student_ID }.)

Using a test that you wrap all the code inside your for .. in loop, typeof RewardPurchases.PurchasesArray[i] === 'object' && typeof RewardPurchases.PurchasesArray[i] !== null should do the trick, ensuring that each property that you use in your iterations is simply an object, and not a function or some "scalar" value.

NB: You can also use RewardPurchases.PurchasesArray[i].hasOwnProperty('propertyName'), but it isn't supported universally in all browsers, so the above example I gave is safer and works for your purpose.

Solution 2:

What is the integrity of your array like?

//RewardPurchases.PurchasesArray[0] undefined
[1] { Student_Name: undefined }
[2] { Student_Name: 'Bob' }

The above are all valid in an array. [0] and [1] will both give you the error you received.

If PurchasesArray is not an array but an object - then you need to do a check inside your loop.

for (vari in RewardPurchases.PurchasesArray) {
   if(!RewardPurchases.PurchasesArray.hasOwnProperty(i)) {
     continue;
   }

   //rest of code...
}

Post a Comment for "Javascript - "variable Undefined" In One Part Of Loop, Working In A Different Part"