我试图在 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 中可能类似于返回构造函数,如 String
、Array
, ETC。)。因此,在使用 typeof
时,您将始终与 "object"
、"string"
、"undefined"等字符串进行比较
等
关于javascript - 遇到 undefined 的问题 !== undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10587566/