JavaScript - "variable Undefined" In One Part Of Loop, Working In A Different Part
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 (var i 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"