JavaScript中判断函数、变量是否存在的方法:
一、是否存在指定函数
function isExitsFunction(funcName) {
try {
if (typeof(eval(funcName)) == "function") {
return true;
}
} catch(e) {}
return false;
}
二、类似PHP常用的判断函数是否存在,不存在则创建
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
三、判断js函数是否存在,如果存在则执行
假设funcName为函数名字,用如下方法就可以达到目标
一定要添加try catch块,否则不起作用。
try
{
if(typeof(eval(funcName))=="function")
{
funcName();
}
}catch(e)
{
//alert("not function");
}
四、是否存在指定变量
function isExitsVariable(variableName) {
try {
if (typeof(variableName) == "undefined") {
//alert("value is undefined");
return false;
} else {
//alert("value is true");
return true;
}
} catch(e) {}
return false;
}
一般情况下,我们单独判断变量是否存在都是用
if("undefined" != typeof downlm){
if(downlm=="soft"){
document.write('成功');
}
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)