javascript - 遇到 undefined 的问题 !== undefined

标签 javascript jquery ajax types

我试图在 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 = "";
        }
      });
    }

最佳答案

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

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

编辑 - 更多信息:

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

The typeof operator returns a string indicating the type of the unevaluated operand.

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

关于javascript - 遇到 undefined 的问题 !== undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587566/

相关文章:

javascript - 计算后总值(value)不变

javascript - (jQuery) 为正则表达式列出定义的 CSS 类;使用特定的 CSS 来避免安全错误

jquery - 自定义最小 JS/CSS 幻灯片中的幻灯片

javascript - 从 Modal 提交输入到 Div

javascript - Cookie 过期回调

javascript - 我如何给div平等的位置权力

javascript - Jquery 在点击时执行两个函数

javascript - 使用 JQuery 调整/强制 Z 索引

javascript - $.post 不发送数据到 php 脚本

php - 使用ajax更新mysql数据库