最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Having trouble with undefined !== undefined - Stack Overflow

programmeradmin2浏览0评论

I'm trying to process a plete function in an ajax call. If the value is undefined, I want cast a var as an empty string. Otherwise, I would like to capture the value into a string array.

The problem is I'm entering the if statement, even when logging the value of the variable in question returns as undefined. What am I missing here?

pletefunc: 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 = "";
        }
      });
    }

I'm trying to process a plete function in an ajax call. If the value is undefined, I want cast a var as an empty string. Otherwise, I would like to capture the value into a string array.

The problem is I'm entering the if statement, even when logging the value of the variable in question returns as undefined. What am I missing here?

pletefunc: 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 = "";
        }
      });
    }
Share Improve this question asked May 14, 2012 at 16:42 WesleyWesley 5,6209 gold badges46 silver badges72 bronze badges 2
  • 1 Have a look at this previous question : stackoverflow./questions/776950/… – web_bod Commented May 14, 2012 at 16:47
  • @web_bod that looked to be more in terms of paring == to ===, meaning null == undefined = true, whereas null === undefined = false – Wesley Commented May 14, 2012 at 16:50
Add a ment  | 

2 Answers 2

Reset to default 16

typeof returns a string value, so you'll need to pare with "undefined" as a string. E.g.,

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

Edit - more info:

If you check out the MDN page for typeof, you'll see this:

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

This is very different from returning the Type itself (which in JavaScript would probably be something like returning a constructor function like String, Array, etc.). Therefore, when using typeof, you'll always be paring to strings like "object", "string", "undefined", etc.

if($(this).attr("own_Products")){
       arr = $(this).attr("ows_Products").split(',');
}else{
       arr=""
}
发布评论

评论列表(0)

  1. 暂无评论