There are two types of undefined properties: those which have not been defined, and those which have been set to undefined
.
If you need to detect properties which have not been defined on on object (or array), use Object.prototype.hasOwnProperty()
, like so:
for (var i = 0; i < result.length; i++) {
if (!Object.prototype.hasOwnProperty.call(window, 'user' + i)) {
window['user' + i] = // DO SOMETHING WITH THE VARIABLE WHICH IS NOT DEFINED
}
}
Since window
is an Object, you can also call hasOwnProperty
directly through it, if you trust that nobody has set it (or Object.prototype.hasOwnProperty
, which window
inherits) to something else. The code for that would look like this:
for (var i = 0; i < result.length; i++) {
if (!window.hasOwnProperty('user' + i)) {
window['user' + i] = // DO SOMETHING WITH THE VARIABLE WHICH IS NOT DEFINED
}
}
If you need to specifically detect properties set to undefined
, then start with the previous check and if true, check the value. Assuming that no one has changed window.hasOwnProperty
, that would look like this:
for (var i = 0; i < result.length; i++) {
if (window.hasOwnProperty('user' + i) && window['user' + i] === undefined) {
window['user' + i] = // DO SOMETHING WITH THE VARIABLE WHICH IS NOT DEFINED
}
}
You may also need to check for properties that are undefined, or set to undefined
or null
. Again assuming that no one has changed window.hasOwnProperty
, that might look like this:
for (var i = 0; i < result.length; i++) {
if (!window.hasOwnProperty('user' + i) || window['user' + i] === undefined || window['user' + i] === null) {
window['user' + i] = // DO SOMETHING WITH THE VARIABLE WHICH IS NOT DEFINED
}
}