如何访问 JavaScript 属性?
访问 JavaScript 属性有三种方法 −
- 使用圆点属性访问:对象.属性
- 使用方括号表示法:对象['属性']
- 使用对象解构:let {属性} = 对象
以下是访问 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, .sample { font-size: 18px; font-weight: 500; color: blueviolet; } .sample { color: red; } </style> </head> <body> <h1>Access JavaScript object properties</h1> <div><pre class="sample">{a:22,b:44}</pre></div> <div class="result"></div> <button class="Btn">Access</button> <h3>Click on the above button to access object properites</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let obj = { a: 22, b: 44 }; BtnEle.addEventListener("click", () => { resEle.innerHTML += "obj.a = " + obj.a + "<br>"; resEle.innerHTML += "obj['a'] = " + obj["a"] + "<br>"; let { a } = obj; resEle.innerHTML += "{a}=obj = " + a + "<br>"; }); </script> </body> </html>
输出
点击 ‘访问’ 按钮 −
广告