if(xxx){console.log(1)}else{console.log(2)}, xxx可以是哪些常见类型输出2?

问题:if(xxx){console.log(1)}else{console.log(2)},输出为2的类型有哪些?

解答

当我们用 if 做判断的时候,if 后面的括号里表达式的值必须是布尔型,比如

if(a > 1){
    console.log('a>1')
}
if(b === 3 || c > 4){
   console.log('hello')
}

如果括号里是其他写法,则会把运算后的值强制转换为布尔型,如

if(1){     // Boolean(1) -> true
   console.log('hello')
}

if( a = 3 ){   // a = 3 的结果是3, Boolean(3) -> true
   console.log('hello')
}

if( a = 0 ){   // a = 0 的结果是3, Boolean(0) -> false
   console.log('hello')
}else{
   console.log('world')   // 输出world
}

强制转换结果为 falsy的值基础类型有6个:

  • false
  • 0
  • ”, 注意这里是空字符串,不是 ‘ ‘
  • null
  • undefined
  • NaN

看下面几个例子:

var a;
if(a){console.log(1)}else{console.log(2)}   //输出2

if(""){console.log(1)}else{console.log(2)}   //输出2

if(a=null){console.log(1)}else{console.log(2)} //输出2, a=null的结果是null

if(1/'a'){console.log(1)}else{console.log(2)} //输出2, 1/'a'为NaN

if(parseInt('123hello')){  //parseInt('123hello') -> '123' -> true
    console.log(1)
}else{
    console.log(2)
}

if(Number('123hello')){  //Number('123hello') -> NaN -> false
    console.log(1)
}else{
    console.log(2)
}

从上面的例子可以看出直接做判断代码的可读性很差,一不留神就埋下了难以察觉的祸根。

所以我们建议用 === 做精准判断,比如:

if(a === ''){console.log(1)} else{console.log(2)}

但 NaN的判断除外

if( 1/'a' === NaN) {console.log(1)} else{console.log(2)}  //输出2
if(isNaN(1/'a')) {console.log(1)} else{console.log(2)}   //输出1

还有一点需要注意,对于 函数、数组、对象、正则… 这些引用类型,Boolean 强制转换后结果都是 true, 如:

if( {} ){console.log(1)} else{console.log(2)}  // 输出1
if( [] ){console.log(1)} else{console.log(2)}  // 输出1
if(document.body){console.log(1)} else{console.log(2)}   //输出1

但有一个对象例外: document.all, 参考前面每日一题 「每日一题」为什么 document.all 有时像一个对象,有时又不像一个对象 – 前端学习指南 – 知乎专栏

if( document.all ) {console.log(1)} else{console.log(2)}  // 输出2

作者:若愚,想学前端?进群

93 thoughts on “if(xxx){console.log(1)}else{console.log(2)}, xxx可以是哪些常见类型输出2?”

  1. Pretty part of content. I just stumbled upon your web site and in accession capital to say that I get in fact enjoyed account your blog posts. Anyway I’ll be subscribing in your augment and even I fulfillment you get entry to constantly rapidly.|

  2. Hello there! I could have sworn I’ve been to this web site before but after looking at some of the posts I realized it’s new to me. Regardless, I’m certainly happy I found it and I’ll be book-marking it and checking back regularly!|

  3. Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is magnificent, as well as the content!|

  4. Helpful information. Fortunate me I found your site unintentionally, and I’m stunned why this accident did not took place in advance! I bookmarked it.|

  5. I just like the helpful information you supply for your articles. I will bookmark your blog and take a look at once more here frequently. I’m reasonably certain I will be told many new stuff right here! Best of luck for the next!|

  6. Excellent blog right here! Also your website loads up fast! What web host are you the usage of? Can I am getting your affiliate hyperlink to your host? I wish my website loaded up as fast as yours lol|

  7. magnificent publish, very informative. I wonder why the other specialists of this sector don’t understand this. You must continue your writing. I am confident, you have a huge readers’ base already!|

  8. I blog quite often and I genuinely appreciate your content. This article has truly peaked my interest. I will bookmark your website and keep checking for new details about once a week. I subscribed to your Feed as well.|

  9. Hello there! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that cover the same subjects? Thanks a lot!|

  10. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog? My blog is in the very same niche as yours and my users would really benefit from a lot of the information you present here. Please let me know if this alright with you. Many thanks!|

  11. Do you have a spam problem on this website; I also am a blogger, and I was wanting to know your situation; we have developed some nice practices and we are looking to exchange strategies with other folks, be sure to shoot me an email if interested.|

  12. I got this web page from my pal who told me about this web page and at the moment this time I am browsing this web site and reading very informative articles here.|

  13. I’ll right away seize your rss feed as I can’t to find
    your email subscription link or newsletter service.
    Do you’ve any? Kindly permit me recognize so that I may subscribe.
    Thanks.

  14. I love what you guys are up too. This kind of clever work and exposure!
    Keep up the great works guys I’ve included you guys
    to our blogroll.

  15. Wonderful blog! I found it while browsing on Yahoo News.
    Do you have any suggestions on how to get listed
    in Yahoo News? I’ve been trying for a while but I never seem to get there!
    Thank you

  16. Thanks , I’ve recently been looking for information about this subject for a while and yours is the greatest I’ve came upon so far. However, what about the conclusion? Are you positive concerning the source?|

  17. Hello there! This is kind of off topic but I need some help from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about making my own but I’m not sure where to start. Do you have any tips or suggestions? With thanks|

  18. hello!,I really like your writing very much! share we be in contact extra about your post on AOL? I require an expert on this space to unravel my problem. May be that’s you! Taking a look ahead to look you. |

  19. Wonderful blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers|

  20. Hey there! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.|

  21. Wonderful beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog website? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea|

  22. Does your site have a contact page? I’m having trouble locating it but, I’d like
    to shoot you an email. I’ve got some suggestions for your blog you
    might be interested in hearing. Either way, great site and I look forward to seeing it expand
    over time.

  23. Sweet blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Many thanks|

  24. Thank you a lot for sharing this with all of us you really understand what you are talking about!
    Bookmarked. Kindly also visit my web site =). We can have a
    hyperlink change agreement between us

  25. Today, I went to the beach with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!|

  26. Greetings! Very useful advice within this article! It is the little changes which will make the most significant changes. Many thanks for sharing!|

  27. Hi there to all, how is everything, I think every one is getting more from this site, and your views are good in support of new people.|

  28. hey there and thank you for your info – I have definitely picked up something new from right here. I did however expertise some technical issues using this site, as I experienced to reload the website many times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and could damage your quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for much more of your respective intriguing content. Ensure that you update this again very soon.|

  29. Have you ever thought about adding a little bit more than just
    your articles? I mean, what you say is important and everything.
    Nevertheless imagine if you added some great photos or video clips to give your posts more, “pop”!
    Your content is excellent but with images and clips, this site could undeniably be one of the very best in its field.
    Good blog!

  30. It’s in reality a great and useful piece of info. I am happy that you shared this helpful information with us. Please stay us up to date like this. Thanks for sharing.

  31. I simply wished to say thanks once more. I do not know the things that I would’ve carried out without the smart ideas discussed by you regarding such a subject. It was before the difficult difficulty for me personally, nevertheless being able to view this well-written fashion you dealt with that forced me to jump over delight. I’m happy for this advice and trust you are aware of a great job that you’re getting into teaching most people via your site. I am sure you’ve never met any of us.

  32. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.|

  33. Just want to say your article is as surprising. The clearness in your post is just nice and i can assume you’re an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work.|

  34. Its such as you learn my thoughts! You appear to know a lot approximately this, like you wrote the ebook in it or something. I believe that you just could do with some percent to pressure the message house a little bit, but other than that, that is fantastic blog. A fantastic read. I will definitely be back.|

  35. Hey there would you mind letting me know which hosting company you’re working with? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a honest price? Many thanks, I appreciate it!|

  36. It is the best time to make a few plans for the future and it’s time to be happy. I’ve read this publish and if I may just I want to counsel you few attention-grabbing issues or tips. Perhaps you could write subsequent articles referring to this article. I want to learn more things approximately it!|

  37. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?|

  38. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

  39. I have been surfing on-line greater than 3 hours nowadays, yet I never found any fascinating article like yours. It’s lovely price enough for me. In my view, if all site owners and bloggers made just right content material as you did, the web will likely be a lot more helpful than ever before.|

  40. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if all webmasters and bloggers made good content as you did, the web will be much more useful than ever before.|

  41. Hi, I do think this is an excellent website. I stumbledupon it 😉 I will revisit once again since i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.|

  42. May I just say what a relief to find a person that really knows what they are discussing over the internet. You definitely realize how to bring a problem to light and make it important. More and more people must read this and understand this side of the story. I was surprised that you aren’t more popular because you definitely possess the gift.|

  43. Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?|

  44. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.|

  45. Hello! I’ve been reading your site for some time now and finally got the courage to go ahead and give you a shout out from Humble Tx! Just wanted to mention keep up the good work!|

  46. Thanks for every other informative blog. The place else may I am getting that type of info written in such a perfect means? I have a venture that I am simply now working on, and I’ve been at the look out for such info.|

  47. Everything composed made a ton of sense. However, think on this, what if you were to write a awesome headline? I am not saying your content isn’t solid., but what if you added something that grabbed folk’s attention? I mean BLOG_TITLE is a little vanilla. You should peek at Yahoo’s front page and note how they create article headlines to get viewers to click. You might try adding a video or a picture or two to grab readers excited about everything’ve written. Just my opinion, it would bring your posts a little livelier.|

发表评论

电子邮件地址不会被公开。