字符串插值
<!DOCTYPE html> <html> <body> <h2>JavaScript 模板字面量</h2> <p>模板字面量允许字符串中的变量:</p> <p id="demo"></p> <p>Internet Explorer 不支持模板字面量。</p> <script> var firstName = "John"; var lastName = "Doe"; var text = `Welcome ${firstName}, ${lastName}!`; document.getElementById("demo").innerHTML = text; </script> </body> </html>
模板字面量
<!DOCTYPE html> <html> <body> <h2>JavaScript 模板字面量</h2> <p>模板字面量允许字符串中的变量:</p> <p id="demo"></p> <p>Internet Explorer 不支持模板字面量。</p> <script> let header = "Templates Literals"; let tags = ["template literals", "javascript", "es6"]; let html = `<h2>${header}</h2><ul>`; for (const x of tags) { html += `<li>${x}</li>`; } html += `</ul>`; document.getElementById("demo").innerHTML = html; </script> </body> </html>
确定是否是数
<!DOCTYPE html> <html> <body> <h1>JavaScript 数字</h1> <p>您可使用全局 JavaScript 函数 isNaN() 来确定某个值是否是数:</p> <p id="demo"></p> <script> var x = 100 / "Apple"; document.getElementById("demo").innerHTML = isNaN(x); </script> </body> </html>
超出数字范围
<!DOCTYPE html> <html> <body> <h1>JavaScript 数字</h1> <p>Infinity (或 -Infinity)是 JavaScript 在计算数时超出最大可能数范围时返回的值:</p> <p id="demo"></p> <script> var myNumber = 2; var txt = ""; while (myNumber != Infinity) { myNumber = myNumber * myNumber; txt = txt + myNumber + "<br>"; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>
请不要创建数值对象。这样会拖慢执行速度。
new关键词使代码复杂化,并产生某些无法预料的结果