JavaScript 中的对象初始化器
对象初始化器是一种表达式,它允许我们初始化新创建的对象。它是用一对大括号 {} 括起来的对象的一个由零个或多个属性名和关联值组成的逗号分隔的列表。
以下是 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>Object initializer in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to initialize an object with object initializer and display it</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let name = "Rohan"; let age = 22; let place = "Delhi"; const 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>
输出
单击“点击此处”按钮后 -
广告