简体   繁体   English

我的try / catch代码有什么问题?

[英]What's wrong with my try/catch code?

var tryThis = false
try {
  if (tryThis = true) {
    console.log("Why does this get printed?")
  }
} catch(e) {
  console.log("The error is", e)
}

There's something definitely wrong with my understanding of Javascript's try/catch statements. 我对Javascript的try / catch语句的理解肯定有问题。 I'm new to this so any help would be appreciated! 我对此并不陌生,因此不胜感激!

This line: 这行:

 if (tryThis = true) {

assigns true to tryThis , which evaluates to (as @Tibrogargan commented above) to true . 分配 truetryThis ,其评估对(作为上述@Tibrogargan注释)到true Instead: 代替:

 if (tryThis === true) {

You want to compare the values. 您要比较这些值。 Use === . 使用===

// this is actually assigning `true` to `tryThis`
if (tryThis = true) 

This is just to help you understand how to compare boolean values 这只是为了帮助您了解如何比较布尔值

When you need to make a comparison between boolean values, you don't need to do this: tryThis === true because it's unnecessary. 当需要在布尔值之间进行比较时,不需要这样做: tryThis === true因为它是不必要的。

var tryThis = false
try {
  if (tryThis === true) {
              ^

Just use the boolean value as follow: 只需使用布尔值,如下所示:

var tryThis = false
try {
  if (tryThis) { // this is the same as tryThis === true or tryThis !== false
      ^

If you want to compare a boolean value to false, don't do this: 如果要将布尔值与false进行比较,请不要这样做:

 tryThis === false
         ^

Rather, use the negation operator, so, do the following: 而是,使用否定运算符,因此,请执行以下操作:

 !tryThis
 ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM