简体   繁体   English

如果语句不起作用并且未定义

[英]if statment not working and getting undefined

I have a code which add a class on my navbar, this class will be added only on specific pages.我有一个在我的导航栏上添加一个类的代码,这个类只会添加到特定页面上。 I check which pages like this pathName= window.location.pathname.split('/');我检查哪些页面像这样pathName= window.location.pathname.split('/'); this code returns me an array with the splited path, then I use the foreach loop to check if this page matches the requirements.此代码返回一个带有分割路径的数组,然后我使用foreach循环来检查此页面是否符合要求。 If it does, the path will be undefined.如果是,路径将是未定义的。 But my if statment doesn't work because, I get this error Cannot read properties of undefined (reading '2')但是我的if语句不起作用,因为我收到此错误Cannot read properties of undefined (reading '2')

The method where I'm getting a path我获取路径的方法

let pathName;
$(window).on('load', function () {
    if($('.owl-item').length<5){
    }
    pathName= window.location.pathname.split('/');
}

My scrolling method我的滚动方法

$(window).scroll(function (evt) {
        if(pathName[2]===undefined) the line where I getting the error{
            **something**
            }else{
                **something**
            }
        }

I have solved the problem I changed my if statment to this我已经解决了问题,我将 if 语句更改为此

Before

$(window).scroll(function (evt) {
        if(pathName[2]===undefined) **this** {
            **something**
            }else{
                **something**
            }
        }

After

$(window).scroll(function (evt) {
        if(typeof pathName[2]==='undefined') **to this**{
            **something**
            }else{
                **something**
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM