Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Operators ใน JavaScript คืออะไร?

นิพจน์ง่ายๆ 4 + 5 = 9 ที่นี่ 4 และ 5 เรียกว่า operands และ + เรียกว่า operator

JavaScript รองรับ operators ประเภทต่อไปนี้:

  • Arithmetic Operators (คณิตศาสตร์)
  • Comparison Operators (เปรียบเทียบ)
  • Logical/Relational Operators (ตรรกะ)
  • Assignment Operators (กำหนดค่า)
  • Conditional/Ternary Operators (เงื่อนไข)

ตัวอย่าง

<html> 
  <body> 
    <script> 
      var a = 33, b = 10, c = "Test", linebreak = "<br />"; 
      document.write("a + b = "); result = a + b; document.write(result); document.write(linebreak); 
      document.write("a - b = "); result = a - b; document.write(result); document.write(linebreak); 
      document.write("a / b = "); result = a / b; document.write(result); document.write(linebreak); 
      document.write("a % b = "); result = a % b; document.write(result); document.write(linebreak); 
      document.write("a + b + c = "); result = a + b + c; document.write(result); document.write(linebreak); 
      a = ++a; document.write("++a = "); result = ++a; document.write(result); document.write(linebreak); 
      b = --b; document.write("--b = "); result = --b; document.write(result); document.write(linebreak); 
    </script> 
  </body> 
</html>

Operator Types เพิ่มเติม (Modern JS)

ประเภทOperators
Arithmetic+, -, *, /, %, **, ++, --
Comparison==, ===, !=, !==, >, <, >=, <=
Logical&&, ||, !, ?? (nullish coalescing)
Assignment=, +=, -=, *=, /=, %=, **=, &&=, ||=, ??=
Bitwise&, |, ^, ~, <<, >>, >>>
String+ (concat), +=
Typetypeof, instanceof, in, delete
Other?, :, , (comma), => (arrow), ... (spread/rest)

Operator Precedence (ลำดับความสำคัญ)

สูงสุด → ต่ำสุด: () → ++ -- → ** → * / % → + - → < <= > >= → == === != !== → && → || → ?? → ? : → = += -= ... → ,