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

Multiplication Operator (*) ใน JavaScript คืออะไร? ตัวอย่างการใช้งาน

Multiplication Operator (*) ใน JavaScript

ตัวดำเนินการคูณ (*) ใช้สำหรับ คูณค่าของ Operand สองตัว เข้าด้วยกัน ผลลัพธ์จะเป็นตัวเลข (Number)

รูปแบบไวยากรณ์ (Syntax)

result = operand1 * operand2;

ตัวอย่างโค้ด

<html>
  <body>
    <script>
      var a = 33;
      var b = 10;
      document.write("a * b = ");
      result = a * b;
      document.write(result);  // แสดงผล: 330
    </script>
  </body>
</html>

รายละเอียดเพิ่มเติม

  • ถ้า Operand ไม่ใช่ตัวเลข JavaScript จะพยายามแปลงเป็นตัวเลขก่อนคูณ (Type Coercion)
  • 5 * "2" → 10 (String "2" ถูกแปลงเป็น Number)
  • 5 * "hello" → NaN (Not a Number)
  • Infinity * 0 → NaN
  • รองรับ BigInt: 9007199254740991n * 2n → 18014398509481982n

ตัวอย่างเพิ่มเติม

console.log(5 * 2);        // 10
console.log(3.14 * 2);     // 6.28
console.log(-5 * 4);       // -20
console.log(0 * 100);      // 0
console.log(10 * "5");     // 50 (Type Coercion)
console.log(10 * "abc");   // NaN