什么是 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,.sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>JavaScript type coercion</h1> <div class="sample">22</div> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to add the above number with 5.</h3> <script> let sampleEle = document.querySelector('.sample'); let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = ' "22" + 5 = ' + sampleEle.innerHTML+5; }); </script> </body> </html>
输出
以上代码将产生以下输出 −
单击“单击此处”按钮 −
广告