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

Operators ใหม่ล่าสุดที่เพิ่มเข้ามาใน JavaScript คืออะไร?

Operators ใหม่ล่าสุดที่เพิ่มเข้ามาใน JavaScript คือ Spread operator และ Rest operator

Rest Operator

ด้วย rest parameter สามารถแทน arguments หลายค่าเป็น array ได้ ES6 นำมาแสดงด้วย ... นำหน้าพารามิเตอร์

ตัวอย่าง

<html> 
  <body> 
    <script> 
      function addition(...numbers) { 
        var res = 0; 
        numbers.forEach(function(number) { 
          res += number; 
        }); 
        return res; 
      } 
      document.write(addition(3)); 
      document.write(addition(9,10,11,12,13)); 
    </script> 
  </body> 
</html>

Spread Operator

อนุญาตให้ expression ขยายเป็น multiple arguments, elements, variables ฯลฯ

ตัวอย่าง

<html> 
  <body> 
    <script> 
      var a = [10, 20]; 
      var b = "rank"; 
      var c = [30, "points"]; 
      var d = "run"; 
      // concat method
      var e = a.concat(b, c, d); 
      // spread operator
      var f = [...a, b, ...c, d]; 
      document.write(e); 
      document.write("<br>" + f); 
    </script> 
  </body> 
</html>

Operators ใหม่ๆ อื่นๆ (ES2016-ES2024)

OperatorVersionคำอธิบาย
**ES2016Exponentiation (ยกกำลัง)
**=ES2016Exponentiation assignment
?.ES2020Optional chaining
??ES2020Nullish coalescing
??=ES2021Nullish coalescing assignment
||=ES2021Logical OR assignment
&&=ES2021Logical AND assignment
?? (ใน destructuring)ES2021Logical assignment operators

ตัวอย่าง Logical Assignment (ES2021)

let x = 0;
x ??= 10;   // x = 10 (เพราะ x เป็น falsy แต่ไม่ใช่ null/undefined - รอ ไม่ใช่)
x ??= 20;   // x = 10 (ไม่เปลี่ยน เพราะ x ไม่ใช่ null/undefined)

let y = null;
y ??= 10;   // y = 10

let z = "hello";
z ||= "world";  // z = "hello" (ไม่เปลี่ยน เพราะ truthy)
z &&= "world";  // z = "world" (เปลี่ยน เพราะ truthy)