【问题标题】:Having trouble with undefined !== undefined遇到问题 undefined !== undefined
【发布时间】:2012-05-22 04:29:54
【问题描述】:

我正在尝试在 ajax 调用中处理完整的函数。如果值未定义,我想将 var 转换为空字符串。否则,我想将值捕获到字符串数组中。

问题是我正在输入 if 语句,即使将相关变量的值记录为未定义也是如此。我在这里错过了什么?

completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        if(typeof $(this).attr("ows_Products") !== undefined) {
          console.log($(this).attr("ows_Products"));
          arr = $(this).attr("ows_Products").split(',');
        }
        else {
          arr = "";
        }
      });
    }

【问题讨论】:

  • 看看这个之前的问题:stackoverflow.com/questions/776950/…
  • @web_bod 在比较 == 和 === 方面看起来更多,这意味着 null == undefined = true,而 null === undefined = false

标签: javascript jquery ajax types


【解决方案1】:

typeof 返回一个字符串值,因此您需要将"undefined" 作为字符串进行比较。例如,

if(typeof $(this).attr("ows_Products") !== "undefined") { ... }

编辑 - 更多信息:

如果您查看MDN page for typeof,您会看到:

typeof 运算符返回一个字符串,指示未计算的操作数的类型。

这与返回 Type 本身非常不同(在 JavaScript 中可能类似于返回构造函数,如 StringArray 等)。因此,在使用typeof 时,您将始终与"object""string""undefined" 等字符串进行比较。

【讨论】:

  • 啊,是的。有时是小事。
  • 解决方案的简单性通常与您花多长时间盯着问题成反比 :)
  • 哈,谢谢。老实说,我必须感谢我父亲(也是一位拥有多年经验的程序员)的声明。
【解决方案2】:
if($(this).attr("own_Products")){
       arr = $(this).attr("ows_Products").split(',');
}else{
       arr=""
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2021-08-19
    • 2016-12-30
    • 2015-03-03
    相关资源
    最近更新 更多