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

ES6 Property Shorthands ใน JavaScript


ใน ES6 หากชื่อ Key ของออบเจ็กต์และชื่อตัวแปรที่ส่งเป็นค่าคุณสมบัติเหมือนกัน เราสามารถละชื่อ Value ไปได้ และระบุแค่ชื่อ Key เท่านั้น

โค้ดตัวอย่างสำหรับ Property Shorthands ใน JavaScript ด้านล่าง

ตัวอย่าง

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body {     font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .result {       font-size: 20px;       font-weight: 500;       color: blueviolet;    } </style> </head> <body> <h1>ES6 Property Shorthands in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to display the person object</h3> <script>    let resEle = document.querySelector(".result");    let BtnEle = document.querySelector(".Btn");    let name='Rohan',age=16,place='Delhi';    let person = {       name,age,place,    }    BtnEle.addEventListener("click", () => {       resEle.innerHTML = 'person.name = '+person.name+'<br>';       resEle.innerHTML += 'person.age = '+person.age+'<br>';       resEle.innerHTML += 'person.place = '+person.place+'<br>';    }); </script> </body> </html>

ผลลัพธ์

ES6 Property Shorthands ใน JavaScript

เมื่อคลิกปุ่ม ‘CLICK HERE’ −

ES6 Property Shorthands ใน JavaScript