if(!parent[0] || parent[0].style.display !== 'none') {
console.log('1');
}
我试图在一行中完成此操作,但在 Firefox 中失败,给出类型错误,表示parent[0]未定义。但在这里我试图检查并执行 if 循环(如果是)。所以我将其分成两个 if 的唯一解决方案是这样的:
if(!parent[0]) {
console.log('1');
return;
}
if(parent[0].style.display !== 'none') {
console.log('1');
}
如何在一行中完成它?为什么第一个代码失败并说parent[0]未定义,我怎样才能防止这种情况并只执行里面的控制台日志。
最佳答案
这应该可以完成工作:
if(parent[0] && parent[0].style.display !== 'none') {
console.log('1');
}
使用 someVariable && 条件
意味着 someVariable
已定义且满足条件。
在我看来,最易读的代码是:
function doSomething() {
// if condition is not met we quit the function
if(parent[0] === undefined) {
return false;
}
// parent[0] is defined we proceed
// Perhaps other conditions that should quit the function
if(parent[0].style.display === 'none') {
return false;
}
// parent[0] is defined we proceed and all checks are done
// All your logic here
}
关于javascript - 使用 or 检查一个 if 条件中是否未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084255/