Check if a variable is in the scope or not in Javascript
I need to check if a obje开发者_JS百科ct "objCR" is present in the current scope or not. I tried using below code.
if(objCR == null)
alert("object is not defined");
Let me know where I am wrong.
Use the typeof operator:
if(typeof objCR == "undefined")
alert("objCR is not defined");
if (typeof objCR=="undefined"){
alert("objCR is undefined");
} else {
alert("objCR is defined");
};
(!objCR) will return true if objCR is a boolean equal to false
As mentioned by others, using a typeof check will get you some of the way there:
if (typeof objCR == "undefined") {
alert("objCR is undefined");
}
However, this won't distinguish between objCR existing and being undefined (as would be the case if it had been declared but not assigned to, e.g. using var objCR;) and objCR never having been declared anywhere in the scope chain, which I think is what you actually want. If you want to be sure that no objCR variable has even been declared, you could use try/catch as follows:
try {
objCR; // ReferenceError is thrown if objCR is undeclared
} catch (ex) {
alert("objCR has not been declared");
}
I would suggest the obvious:
if (objCR==undefined) ...
I always have this to be safe:
if(typeof objCR == "undefined" || objCR == null)
alert("object is not defined or null");
加载中,请稍侯......
精彩评论