遇到unfined问题!== undefined

Wes*_*ley 5 javascript ajax jquery types

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

问题是我正在输入if语句,即使在记录有问题的变量的值时返回为undefined.我在这里错过了什么?

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 = "";
        }
      });
    }
Run Code Online (Sandbox Code Playgroud)

jma*_*777 16

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

if(typeof $(this).attr("ows_Products") !== "undefined") { ... }
Run Code Online (Sandbox Code Playgroud)

编辑 - 更多信息:

如果您查看MDF页面的typeof,您会看到:

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

这是从返回非常不同的Type本身(这在JavaScript中很可能会像返回一个构造函数一样String,Array等).因此,在使用的时候typeof,你会始终比较像琴弦"object","string","undefined",等.

  • 解决方案的简单性通常与您花费多长时间盯着问题成反比:) (5认同)