JavaScript中如何判断函数、变量是否存在

 4305

JavaScript判断函数、变量是否存在的方法:1、判断是否存在指定函数,代码为【if (typeof(eval(funcName)) == "function")】;2、判断是否存在指定变量。


JavaScript中如何判断函数、变量是否存在


JavaScript中判断函数、变量是否存在的方法:

一、是否存在指定函数

  1. function isExitsFunction(funcName) {
  2.     try {
  3.         if (typeof(eval(funcName)) == "function") {
  4.             return true;
  5.         }
  6.     } catch(e) {}
  7.     return false;
  8. }

二、类似PHP常用的判断函数是否存在,不存在则创建

  1. if (typeof String.prototype.endsWith != 'function') {
  2.     String.prototype.endsWith = function(suffix) {
  3.         return this.indexOf(suffix, this.length - suffix.length) !== -1;
  4.     };
  5. }

三、判断js函数是否存在,如果存在则执行

假设funcName为函数名字,用如下方法就可以达到目标

一定要添加try catch块,否则不起作用。

  1. try
  2. { 
  3.     if(typeof(eval(funcName))=="function") 
  4.     {
  5.         funcName();
  6.     }
  7. }catch(e)
  8. {
  9.     //alert("not function"); 
  10. }

四、是否存在指定变量

  1. function isExitsVariable(variableName) {
  2.     try {
  3.         if (typeof(variableName) == "undefined") {
  4.             //alert("value is undefined"); 
  5.             return false;
  6.         } else {
  7.             //alert("value is true"); 
  8.             return true;
  9.         }
  10.     } catch(e) {}
  11.     return false;
  12. }

一般情况下,我们单独判断变量是否存在都是用

  1. if("undefined" != typeof downlm){ 
  2.     if(downlm=="soft"){ 
  3.         document.write('成功'); 
  4.     } 
  5. }



本文网址:https://www.zztuku.com/index.php/detail-8760.html
站长图库 - JavaScript中如何判断函数、变量是否存在
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐