简体   繁体   中英

How to compare values in JavaScript?

How do I compare values in JavaScript?

My code below should alert "2" but it does not work.

var test_val = "TWO";
 if(test_val = "ONE")
  {
    alert("1");
  }
 else if(test_val = "TWO")
  {
    alert("2");
  }

You have to use comparison operators (==, ===, !=, !==). The == and != are type insensitive and performs an implicit cast on the second operand. The === and !== operands are performing type sensitive comparison that includes type checking.

 var test_val = "TWO";
 if(test_val === "ONE")
 {
     alert("1");
 }
 else if(test_val === "TWO")
 {
     alert("2");
 }

Type Sensitive

//1 === "1" false
//1 === 1   true
//1 !== "1" true
//1 !== 1   false

Type Insensitive

//1 == "1" true
//1 == 1   true
//1 == 2   false
//1 == "2" false

A single = is assignment (Used for setting values)

A double == is used for comparing and will return true/false.

A triple === is used to compare value and type. will return true/false only if the values and types match.

The best ANSWER to this is that whenever you do comparison you CANNOT use = inside the parenthesis. You can use either == or === depending on what you want to compare. Here's what you can do:

  var test_val = "TWO";
  if(test_val == "ONE")
  {
  alert("1");
  }
  else if(test_val == "TWO")
  {
  alert("2");
  }

= is Assignment operator.

use == Relational Operator.

Reference: http://www.tutorialspoint.com/java/java_basic_operators.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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