if语句不工作且未定义



我有一个代码,在我的导航栏上添加一个类,这个类只会在特定的页面上添加。我检查像pathName= window.location.pathname.split('/');这样的页面,这段代码返回给我一个具有分割路径的数组,然后我使用foreach循环来检查该页是否符合要求。如果是,路径将是未定义的。但是我的if声明不起作用因为,我得到了这个错误Cannot read properties of undefined (reading '2')

获取路径的方法

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

滚动方法

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

我已经解决了这个问题,我把我的if语句改成了这个

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

相关内容

最新更新