Javascript未定义的问题

时间:2011-12-24 15:32:23

标签: javascript undefined

            if(typeof(GUEST_IDS) != undefined){
          GUEST_IDS = GUEST_IDS.substr(1);
          GUEST_IDS = GUEST_IDS.split(",");
          for(GP in GUEST_POINTS){
            GUEST_ON = 0;
            for(GID in GUEST_IDS){
              if(GUEST_IDS[GID] == GP){
                GUEST_ON = 1;
              }
            }
            if(GUEST_ON == 0){
              GUEST_POINTS[GP].setVisible(false);
            }
          }
        }else{
          for(GP in GUEST_POINTS){
            GUEST_POINTS[GP].setVisible(false);
          }
        }

当我提醒GUEST_IDS时它表示未定义,所以如果GUEST_IDS =未定义为什么代码运行就像if(typeof(GUEST_IDS)!= undefined){是真的?

1 个答案:

答案 0 :(得分:2)

typeof返回指定类型的字符串。另外,typeof不需要parens,最好使用!==而不是!=

if(typeof GUEST_IDS !== "undefined") {

其他要点:

  • 不要把一切都搞好
  • 使用var
  • 使用普通for循环迭代数组;不是for in循环
  • 不要覆盖现有变量; GUEST_IDS正在从字符串更改为数组
  • 使用===而不是==
  • 您可以使用var ids = GUEST_IDS.substr(1).split(",");
  • 之类的链接