繁体   English   中英

检查jQuery / Javascript是否未定义

[英]Checking if undefined in jQuery/Javascript

我有以下几点:

var currentQuestion = $(this).closest(".question")

我已经尝试过在这个这个这个问题中建议的所有内容:

if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)

但是它一直在if语句里面...

我在if里面有这个:

console.log("nextQ: " + currentQuestion.data("index"));

nextQ: undefined正在被打印出来

还有其他想法吗?

编辑:

currentQuestion.data("index") != null

解决了。 如果您检查了我之前尝试过的所有选项,则与此类似的选项具有以下比较元素: !==而不是!= 这种变化带来了不同。 如果有人可以解释原因,我会给他/她正确的答案。

结果永远不会是不确定的,它始终是jQuery对象。 如果该操作未找到任何元素,则jQuery对象将为空,因此您检查其中有多少个元素以查看是否找到了任何东西:

if (currentQuestion.length > 0)

检查jQuery对象中实际上是否有任何元素之后,可以检查是否有任何与该元素相关联的数据。

如果没有数据与元素关联,则当您尝试读取值时, data方法将返回undefined 因此,要检查是否没有数据,应检查data方法返回的值的类型:

if (typeof currentQuestion.data("index") != "undefined")

您想要的是currentQuestion.length

jQuery选择器返回与选择器匹配的元素数组。 要测试数组中的值,应使用length

Boolean([].length); //false

由于0的计算结果为false,因此可以只使用if (currentQuestion.length)

如果您尝试检查它是否为假,请使用!

if (!currentQuestion.length)

对于为什么!=起作用但!==无效的问题,我建议以下问题: JavaScript中==和===之间的区别

基本上, currentQuestion.data('index')并不严格等于null ,但是它可以评估为null :与[] == 0评估为true ,但是[] === 0评估为false

如果要检查是否存在任何元素,请检查长度。

var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
    console.log("nextQ: " + currentQuestion.data("index"));
}
if (currentQuestion.length) {

应该工作正常。 如果它进入那里,它发现了一些东西。 而不是查看if语句,您需要查看html并查看所找到的内容。

这可能不是最优雅的解决方案。 但是不知何故

currentQuestion.data("index") != null

解决了。 如果您检查了我之前尝试过的所有选项,则与此最类似的选项具有以下比较元素: !==而不是!= 这种变化带来了不同。 如果有人可以解释原因,我会给他/她正确的答案。

暂无
暂无

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

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