JavaScript示例
目录:
一. JavaScript能做什么?
二. 在哪里插入JavaScript
三. JavaScript输出
四. JavaScript语法
五. JavaScript语句
六. JavaScript注释
七. JavaScript变量
八. JavaScript算术
九. JavaScript赋值
十. JavaScript字符串连接
十一. JavaScript数据类型
十二. JavaScript对象
十三 . JavaScript函数
十四. JavaScript事件
十五. JavaScript字符串
十六. JavaScript数字
十七. JavaScript数字方法
十八. JavaScript数学
十九. JavaScript 随机
二十. JavaScript日期
二十一. JavaScript数组
二十二. JavaScript数组方法
二十三. JavaScript数组排序
二十四. JavaScript数组迭代
二十五. JavaScript类型转换
二十六. JavaScript布尔值
二十七. JavaScript比较
二十八. JavaScript 条件
二十九. JavaScript循环
三十. JavaScript错误处理
三十一. JavaScript正则表达式
三十二. JavaScript对象
三十二. JavaScript对象属性
三十三. JSON对象
三十四. JSON数组
三十五. JSON解析
三十六. JSON字符串化
三十七. JSON PHP
三十八. JSON HTML
三十九. JSON JSONP
一. JavaScript能做什么?
1.1 JavaScript可以改变HTML内容
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p id="demo">JavaScript can change HTML content.</p> <button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button> </body> </html>
1.2 JavaScript可以改变HTML属性
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p>JavaScript can change HTML attribute values.</p> <p>In this case JavaScript changes the value of the src (source) attribute of an image.</p> <button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button> <img id="myImage" src="pic_bulboff.gif" style="width:100px"> <button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button> </body> </html>
1.3 JavaScript可以改变CSS样式
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p id="demo">JavaScript can change the style of an HTML element.</p> <button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button> </body> </html>
1.4 JavaScript可以隐藏HTM元素
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p id="demo">JavaScript can hide HTML elements.</p> <button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button> </body> </html>
1.5 JavaScript可以显示隐藏HTML元素
<!DOCTYPE html> <html> <body> <h2>What Can JavaScript Do?</h2> <p>JavaScript can show hidden HTML elements.</p> <p id="demo" style="display:none">Hello JavaScript!</p> <button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button> </body> </html>
二. 在哪里插入JavaScript
2.1 <head>中的JavaScript
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </head> <body> <h2>Demo JavaScript in Head</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> </body> </html>
2.2 <body>中的JavaScript
<!DOCTYPE html> <html> <body> <h2>Demo JavaScript in Body</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </body> </html>
2.3 外部文件中的JavaScript
<!DOCTYPE html> <html> <body> <h2>Demo External JavaScript</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <p>This example links to "myScript.js".</p> <p>(myFunction is stored in "myScript.js")</p> <script src="myScript.js"></script> </body> </html>
2.4 外部的URL中的JavaScript
<!DOCTYPE html> <html> <body> <h2>External JavaScript</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Click Me</button> <p>This example uses a full web URL to link to "myScript.js".</p> <p>(myFunction is stored in "myScript.js")</p> <script src="https://www.w3schools.com/js/myScript.js"></script> </body> </html>
2.5 外部文件中的JavaScript
<!DOCTYPE html> <html> <body> <h2>External JavaScript</h2> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <p>This example uses a file path to link to "myScript.js".</p> <p>(myFunction is stored in "myScript.js")</p> <script src="/js/myScript.js"></script> </body> </html>
三. JavaScript输出
3.1. 写入HTML输出
<!DOCTYPE html> <html> <body> <h2>My First Web Page</h2> <p>My first paragraph.</p> <p>Never call document.write after the document has finished loading. It will overwrite the whole document.</p> <script> document.write(5 + 6); </script> </body> </html>
3.2. 写入HTML元素
<!DOCTYPE html> <html> <body> <h2>My First Web Page</h2> <p>My First Paragraph.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
3.3 写入窗口警报框
<!DOCTYPE html> <html> <body> <h2>My First Web Page</h2> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
3.4 写入浏览器控制台
<!DOCTYPE html> <html> <body> <h2>Activate Debugging</h2> <p>F12 on your keyboard will activate debugging.</p> <p>Then select "Console" in the debugger menu.</p> <p>Then click Run again.</p> <script> console.log(5 + 6); </script> </body> </html>
四. JavaScript语法
4.1 JavaScript语句
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p> <p id="demo"></p> <script> var x, y, z; // Declare 3 variables x = 5; // Assign the value 5 to x y = 6; // Assign the value 6 to y z = x + y; // Assign the sum of x and y to z document.getElementById("demo").innerHTML = "The value of z is " + z + "."; </script> </body> </html>
4.2 JavaScript数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Number can be written with or without decimals.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 10.50; </script> </body> </html>
4.3 JavaScript字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Strings</h2> <p>Strings can be written with double or single quotes.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 'John Doe'; </script> </body> </html>
4.4 JavaScript变量
<!DOCTYPE html> <html> <body> <h2>JavaScript Variables</h2> <p>In this example, x is defined as a variable. Then, x is assigned the value of 6:</p> <p id="demo"></p> <script> let x; x = 6; document.getElementById("demo").innerHTML = x; </script> </body> </html>
4.5 JavaScript运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>JavaScript uses arithmetic operators to compute values (just like algebra).</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = (5 + 6) * 10; </script> </body> </html>
4.6 JavaScript赋值
<!DOCTYPE html> <html> <body> <h2>Assigning JavaScript Values</h2> <p>In JavaScript the = operator is used to assign values to variables.</p> <p id="demo"></p> <script> let x, y; x = 5; y = 6; document.getElementById("demo").innerHTML = x + y; </script> </body> </html>
4.7 JavaScript表达式(使用常量)
<!DOCTYPE html> <html> <body> <h2>JavaScript Expressions</h2> <p>Expressions compute to values.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 * 10; </script> </body> </html>
4.8 JavaScript表达式(使用字符串)
<!DOCTYPE html> <html> <body> <h2>JavaScript Expressions</h2> <p>Expressions compute to values.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "John" + " " + "Doe"; </script> </body> </html>
4.9 JavaScript表达式(使用变量)
<!DOCTYPE html> <html> <body> <h2>JavaScript Expressions</h2> <p>Expressions compute to values.</p> <p id="demo"></p> <script> var x; x = 5; document.getElementById("demo").innerHTML = x * 10; </script> </body> </html>
4.10 JavaScript关键词
<!DOCTYPE html> <html> <body> <h2>The var Keyword Creates Variables</h2> <p id="demo"></p> <script> var x, y; x = 5 + 6; y = x * 10; document.getElementById("demo").innerHTML = y; </script> </body> </html>
4.11 JavaScript注释
<!DOCTYPE html> <html> <body> <h2>JavaScript Comments are NOT Executed</h2> <p id="demo"></p> <script> let x; x = 5; // x = 6; I will not be executed document.getElementById("demo").innerHTML = x; </script> </body> </html>
4.12 JavaScript区分大小写
<!DOCTYPE html> <html> <body> <h2>JavaScript is Case Sensitive</h2> <p>Try to change lastName to lastname.</p> <p id="demo"></p> <script> let lastname, lastName; lastName = "Doe"; lastname = "Peterson"; document.getElementById("demo").innerHTML = lastName; </script> </body> </html>
五. JavaScript语句
5.1 JavaScript语句是对浏览器的命令
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>In HTML, JavaScript statements are executed by the browser.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello Dolly."; </script> </body> </html>
5.2 JavaScript代码是一系列语句
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p> <p id="demo"></p> <script> let x, y, z; // Statement 1 x = 5; // Statement 2 y = 6; // Statement 3 z = x + y; // Statement 4 document.getElementById("demo").innerHTML = "The value of z is " + z + "."; </script> </body> </html>
5.3 JavaScript语句用分号隔开
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>JavaScript statements are separated by semicolons.</p> <p id="demo1"></p> <script> let a, b, c; a = 5; b = 6; c = a + b; document.getElementById("demo1").innerHTML = c; </script> </body> </html>
5.4 允许一行多语句
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>Multiple statements on one line are allowed.</p> <p id="demo1"></p> <script> let a, b, c; a = 5; b = 6; c = a + b; document.getElementById("demo1").innerHTML = c; </script> </body> </html>
5.5 JavaScript语句可以在代码块中组合在一块
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p>JavaScript code blocks are written between { and }</p> <button type="button" onclick="myFunction()">Click Me!</button> <p id="demo1"></p> <p id="demo2"></p> <script> function myFunction() { document.getElementById("demo1").innerHTML = "Hello Dolly!"; document.getElementById("demo2").innerHTML = "How are you?"; } </script> </body> </html>
5.6 您可以在运算符或逗号之后断开代码行
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p> The best place to break a code line is after an operator or a comma. </p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello Dolly!"; </script> </body> </html>
六. JavaScript注释
6.1 单行注释
<!DOCTYPE html> <html> <body> <h1 id="myH"></h1> <p id="myP"></p> <script> // Change heading: document.getElementById("myH").innerHTML = "JavaScript Comments"; // Change paragraph: document.getElementById("myP").innerHTML = "My first paragraph."; </script> </body> </html>
6.2 行眉的单行注释
<!DOCTYPE html> <html> <body> <h2>JavaScript Comments</h2> <p id="demo"></p> <script> let x = 5; // Declare x, give it the value of 5 let y = x + 2; // Declare y, give it the value of x + 2 // Write y to demo: document.getElementById("demo").innerHTML = y; </script> </body> </html>
6.3 多行注释
<!DOCTYPE html> <html> <body> <h1 id="myH"></h1> <p id="myP"></p> <script> /* The code below will change the heading with id = "myH" and the paragraph with id = "myP" */ document.getElementById("myH").innerHTML = "JavaScript Comments"; document.getElementById("myP").innerHTML = "My first paragraph."; </script> </body> </html>
6.4 单行注释以防止执行
<!DOCTYPE html> <html> <body> <h2>JavaScript Comments</h2> <h1 id="myH"></h1> <p id="myP"></p> <script> //document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; </script> <p>The line starting with // is not executed.</p> </body> </html>
6.5 多行注释以防止执行
<!DOCTYPE html> <html> <body> <h2>JavaScript Comments</h2> <h1 id="myH"></h1> <p id="myP"></p> <script> /* document.getElementById("myH").innerHTML = "Welcome to my Homepage"; document.getElementById("myP").innerHTML = "This is my first paragraph."; */ document.getElementById("myP").innerHTML = "The comment-block is not executed."; </script> </body> </html>
七. JavaScript变量
7.1 JavaScript变量
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>In this example, x, y, and z are variables.</p> <p id="demo"></p> <script> var x = 5; var y = 6; var z = x + y; document.getElementById("demo").innerHTML = "The value of z is: " + z; </script> </body> </html>
7.2 JavaScript变量作为代数
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>In this example, price, price2, and total are variables.</p> <p id="demo"></p> <script> const price1 = 5; const price2 = 6; let total = price1 + price2; document.getElementById("demo").innerHTML = "The total is: " + total; </script> </body> </html>
7.3 JavaScript数字和字符串
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>Strings are written with quotes.</p> <p>Numbers are written without quotes.</p> <p id="demo"></p> <script> const pi = 3.14; let person = "John Doe"; let answer = 'Yes I am!'; document.getElementById("demo").innerHTML = pi + "<br>" + person + "<br>" + answer; </script> </body> </html>
7.4 JavaScript关键字
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>Create a variable, assign a value to it, and display it:</p> <p id="demo"></p> <script> let carName = "Volvo"; document.getElementById("demo").innerHTML = carName; </script> </body> </html>
7.5 在一个语句中声名多个变量
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>You can declare many variables in one statement.</p> <p id="demo"></p> <script> let person = "John Doe", carName = "Volvo", price = 200; document.getElementById("demo").innerHTML = carName; </script> </body> </html>
7.6 没有值的变量返回值undefined
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>A variable without a value has the value of:</p> <p id="demo"></p> <script> let carName; document.getElementById("demo").innerHTML = carName; </script> </body> </html>
7.7 重新声明变量不会破坏值
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>If you re-declare a JavaScript variable, it will not lose its value.</p> <p id="demo"></p> <script> var carName = "Volvo"; var carName; document.getElementById("demo").innerHTML = carName; </script> </body> </html>
7.8 添加JavaScript数字
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>The result of adding 5 + 2 + 3 is:</p> <p id="demo"></p> <script> let x = 5 + 2 + 3; document.getElementById("demo").innerHTML = x; </script> </body> </html>
7.9 添加JavaScript字符串
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>The result of adding "John" + " " + "Doe" is:</p> <p id="demo"></p> <script> let x = "John" + " " + "Doe"; document.getElementById("demo").innerHTML = x; </script> </body> </html>
7.10 添加字符串和数字
<!DOCTYPE html> <html> <body> <h1>JavaScript Variables</h1> <p>The result of adding "5" + 2 + 3 is:</p> <p id="demo"></p> <script> let x = "5" + 2 + 3; document.getElementById("demo").innerHTML = x; </script> </body> </html>
八. JavaScript算术
8.1 加法(+)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Arithmetic</h2> <h3>The + Operator</h3> <p id="demo"></p> <script> let x = 5; let y = 2; let z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
8.2 减法(-)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Arithmetic</h2> <h3>The - Operator</h3> <p id="demo"></p> <script> let x = 5; let y = 2; let z = x - y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
8.3 乘法(*)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Arithmetic</h2> <h3>The * Operator</h3> <p id="demo"></p> <script> let x = 5; let y = 2; let z = x * y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
8.4 除法(/)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Arithmetic</h2> <h3>The / Operator</h3> <p id="demo"></p> <script> let x = 5; let y = 2; let z = x / y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
8.5 取模(%)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Arithmetic</h2> <h3>The % Operator</h3> <p id="demo"></p> <script> let x = 5; let y = 2; let z = x % y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
8.6 增量(++)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>In this example, y is incremented before it is assigned to x (pre-incremented).</p> <p id="demo1"></p> <p id="demo2"></p> <script> var y = 5; var x = ++y; document.getElementById("demo1").innerHTML = y; document.getElementById("demo2").innerHTML = x; </script> </body> </html>
8.7 减量(--)运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>In this example, y is decremented before it is assigned to x (pre-decremented).</p> <p id="demo1"></p> <p id="demo2"></p> <script> var y = 5; var x = --y; document.getElementById("demo1").innerHTML = y; document.getElementById("demo2").innerHTML = x; </script> </body> </html>
九. JavaScript赋值
9.1 =赋值运算符
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <h3>The = Operator</h3> <p id="demo"></p> <script> let x = 10; document.getElementById("demo").innerHTML = x; </script> </body> </html>
9.2 +=赋值运算符
<!DOCTYPE html> <html> <body> <h2>The += Operator</h2> <p id="demo"></p> <script> var x = 10; x += 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
9.3 -=赋值运算符
<!DOCTYPE html> <html> <body> <h2>The -= Operator</h2> <p id="demo"></p> <script> var x = 10; x -= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
9.4 *=赋值运算符
<!DOCTYPE html> <html> <body> <h2>The *= Operator</h2> <p id="demo"></p> <script> var x = 10; x *= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
9.5 /=赋值运算符
<!DOCTYPE html> <html> <body> <h2>The /= Operator</h2> <p id="demo"></p> <script> var x = 10; x /= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
9.6 %=赋值运算符
<!DOCTYPE html> <html> <body> <h2>The %= Operator</h2> <p id="demo"></p> <script> var x = 10; x %= 5; document.getElementById("demo").innerHTML = x; </script> </body> </html>
十. JavaScript字符串连接
10.1 使用连接(+)运算符将两个字符串相加
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>The + operator concatenates (adds) strings.</p> <p id="demo"></p> <script> var txt1 = "What a very"; var txt2 = "nice day"; document.getElementById("demo").innerHTML = txt1 + txt2; </script> </body> </html>
10.2 将两个字符串与第一个字符串的空格相加
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>The + operator concatenates (adds) strings.</p> <p id="demo"></p> <script> var txt1 = "What a very "; var txt2 = "nice day"; document.getElementById("demo").innerHTML = txt1 + txt2; </script> </body> </html>
10.3 讲两个字符串加在一起,中间有一个空格
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>The + operator concatenates (adds) strings.</p> <p id="demo"></p> <script> var txt1 = "What a very"; var txt2 = "nice day"; document.getElementById("demo").innerHTML = txt1 + " " + txt2; </script> </body> </html>
10.4 使用+=运算符将两个字符串相加
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>The assignment operator += can concatenate strings.</p> <p id="demo"></p> <script> let text1 = "What a very "; text1 += "nice day"; document.getElementById("demo").innerHTML = text1; </script> </body> </html>
10.5 添加字符串和数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Operators</h2> <p>Adding a number and a string, returns a string.</p> <p id="demo"></p> <script> let x = 5 + 5; let y = "5" + 5; let z = "Hello" + 5; document.getElementById("demo").innerHTML = x + "<br>" + y + "<br>" + z; </script> </body> </html>
十一. JavaScript数据类型(Types)
11.1 声名(创建)字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Strings</h2> <p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p> <p id="demo"></p> <script> let answer1 = "It's alright"; let answer2 = "He is called 'Johnny'"; let answer3 = 'He is called "Johnny"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body> </html>
11.2 声名(创建)数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Numbers can be written with, or without decimals:</p> <p id="demo"></p> <script> let x1 = 34.00; let x2 = 34; let x3 = 3.14; document.getElementById("demo").innerHTML = x1 + "<br>" + x2 + "<br>" + x3; </script> </body> </html>
11.3 声名(创建)一个数组
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>Array indexes are zero-based, which means the first item is [0].</p> <p id="demo"></p> <script> const cars = ["Saab","Volvo","BMW"]; document.getElementById("demo").innerHTML = cars[0]; </script> </body> </html>
11.4 声名(创建)一个对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p id="demo"></p> <script> const person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
11.5 查找变量的类型
<!DOCTYPE html> <html> <body> <p>The typeof operator returns the type of a variable or an expression.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = typeof "" + "<br>" + typeof "John" + "<br>" + typeof "John Doe" + "<br>" + typeof 0 + "<br>" + typeof 314 + "<br>" + typeof 3.14 + "<br>" + typeof (3.14); </script> </body> </html>
11.6 添加两个数字和一个字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript</h2> <p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p> <p id="demo"></p> <script> let x = 16 + 4 + "Volvo"; document.getElementById("demo").innerHTML = x; </script> </body> </html>
11.7 添加一个字符串和两个数字
<!DOCTYPE html> <html> <body> <h2>JavaScript</h2> <p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p> <p id="demo"></p> <script> let x = "Volvo" + 16 + 4; document.getElementById("demo").innerHTML = x; </script> </body> </html>
11.8 未定义的变量
<!DOCTYPE html> <html> <body> <h2>JavaScript</h2> <p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p> <p id="demo"></p> <script> let car; document.getElementById("demo").innerHTML = car + "<br>" + typeof car; </script> </body> </html>
11.9 空变量
<!DOCTYPE html> <html> <body> <h2>JavaScript</h2> <p>An empty string has both a legal value and a type:</p> <p id="demo"></p> <script> let car = ""; document.getElementById("demo").innerHTML = "The value is: " + car + "<br>" + "The type is: " + typeof car; </script> </body> </html>
十二. JavaScript对象(Objects)
12.1 创建一个JavaScript变量
<!DOCTYPE html> <html> <body> <h2>JavaScript Variables</h2> <p id="demo"></p> <script> // Create and display a variable: let car = "Fiat"; document.getElementById("demo").innerHTML = car; </script> </body> </html>
12.2 创建一个JavaScript对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p id="demo"></p> <script> // Create an object: const car = {type:"Fiat", model:"500", color:"white"}; // Display some data from the object: document.getElementById("demo").innerHTML = "The car type is " + car.type; </script> </body> </html>
12.3 创建一个人对象(单行)
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p id="demo"></p> <script> // Create an object: const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; // Display some data from the object: document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
12.4 创建一个人对象(多行)
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p id="demo"></p> <script> // Create an object: const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; // Display some data from the object: document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
12.5 使用.property访问对象属性
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>There are two different ways to access an object property.</p> <p>You can use person.property or person["property"].</p> <p id="demo"></p> <script> // Create an object: const person = { firstName: "John", lastName : "Doe", id : 5566 }; // Display some data from the object: document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; </script> </body> </html>
12.6 使用[property]访问对象属性
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>There are two different ways to access an object property.</p> <p>You can use person.property or person["property"].</p> <p id="demo"></p> <script> // Create an object: const person = { firstName: "John", lastName : "Doe", id : 5566 }; // Display some data from the object: document.getElementById("demo").innerHTML = person["firstName"] + " " + person["lastName"]; </script> </body> </html>
12.7 将函数属性作为方法访问
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>An object method is a function definition, stored as a property value.</p> <p id="demo"></p> <script> // Create an object: const person = { firstName: "John", lastName: "Doe", id: 5566, fullName: function() { return this.firstName + " " + this.lastName; } }; // Display data from the object: document.getElementById("demo").innerHTML = person.fullName(); </script> </body> </html>
12.8 将函数属性作为属性访问
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>If you access an object method without (), it will return the function definition:</p> <p id="demo"></p> <script> // Create an object: const person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; // Display data from the object: document.getElementById("demo").innerHTML = person.fullName; </script> </body> </html>
十三 . JavaScript函数
13.1 一个简单的功能
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World!"; } </script> </head> <body> <p>When you click "Try it", a function will be called.</p> <p>The function will display a message.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> </body> </html>
13.2 带参数的函数
<!DOCTYPE html> <html> <body> <p>Click "Try it" to call a function with arguments</p> <button onclick="myFunction('Harry Potter','Wizard')">Try it</button> <p id="demo"></p> <script> function myFunction(name,job) { document.getElementById("demo").innerHTML = "Welcome " + name + ", the " + job + "."; } </script> </body> </html>
13.3 带参数的函数2
<!DOCTYPE html> <html> <head> <script> function myfunction(txt) { document.getElementById("demo").innerHTML = txt } </script> </head> <body> <p>When you click on one of the buttons, a function will be called. The function will display the argument that is passed to it.</p> <form> <input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"> <input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"> </form> <p id="demo"></p> </body> </html>
13.4 返回值的函数
<!DOCTYPE html> <html> <body> <h2>JavaScript Functions</h2> <p>This example calls a function which performs a calculation and returns the result:</p> <p id="demo"></p> <script> var x = myFunction(4, 3); document.getElementById("demo").innerHTML = x; function myFunction(a, b) { return a * b; } </script> </body> </html>
13.5 将华摄氏度转换为摄氏度的函数
<!DOCTYPE html> <html> <body> <h2>JavaScript Functions</h2> <p>This example calls a function to convert from Fahrenheit to Celsius:</p> <p id="demo"></p> <script> function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius(77); </script> </body> </html>
13.6 没有()的函数
<!DOCTYPE html> <html> <body> <h2>JavaScript Functions</h2> <p>Accessing a function without () will return the function definition instead of the function result:</p> <p id="demo"></p> <script> function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius; </script> </body> </html>
十四. JavaScript事件(Events)
14.1 onclick事件更改HTML元素
<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button> <p id="demo"></p> </body> </html>
14.2 一个onclick事件改变它自己的元素
<!DOCTYPE html> <html> <body> <h2>JavaScript HTML Events</h2> <button onclick="this.innerHTML=Date()">The time is?</button> </body> </html>
14.3 onclick事件调用函数
<!DOCTYPE html> <html> <body> <h2>JavaScript HTML Events</h2> <p>Click the button to display the date.</p> <button onclick="displayDate()">The time is?</button> <script> function displayDate() { document.getElementById("demo").innerHTML = Date(); } </script> <p id="demo"></p> </body> </html>
十五. JavaScript字符串(Strings)
15.1 字符串可以用单引用或双引号编写
<!DOCTYPE html> <html> <body> <h2>JavaScript Strings</h2> <p>Strings are written inside quotes.</p> <p>You can use single or double quotes:</p> <p id="demo"></p> <script> var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60'; document.getElementById("demo").innerHTML = carName1 + " " + carName2; </script> </body> </html>
15.2 显示一些字符串示例
<!DOCTYPE html> <html> <body> <h2>JavaScript Strings</h2> <p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p> <p id="demo"></p> <script> let answer1 = "It's alright"; let answer2 = "He is called 'Johnny'"; let answer3 = 'He is called "Johnny"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body> </html>
15.3 引号前的反斜杆接受引号作为引号
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x = 'It\'s alright'; var y = "We are the so-called \"Vikings\" from the north."; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>
15.4 查找字符串的长度
<!DOCTYPE html> <html> <body> <h2>JavaScript String Properties</h2> <p>The length property returns the length of a string:</p> <p id="demo"></p> <script> let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = text.length; </script> </body> </html>
15.5 您可以使用反斜杠分隔本文字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Strings</h2> <p> You can break a code line within a text string with a backslash. </p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello \ Dolly!"; </script> </body> </html>
15.6 您不能使用反斜杆来破坏代码
<!DOCTYPE html> <html> <body> <h2>JavaScript Statements</h2> <p id="demo">You cannot break a code line with a \ backslash.</p> <script> document.getElementById("demo").innerHTML = \ "Hello Dolly."; </script> </body> </html>
15.7 查找字符串中文本第一次出现的位置-indexOf()
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The indexOf() method returns the position of the first occurrence of a specified text:</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; document.getElementById("demo").innerHTML = str.indexOf("locate"); </script> </body> </html>
15.8 在字符串中搜索文本,如果找到则返回文本-match()
<!DOCTYPE html> <html> <body> <p>Click the button to perfom a global (/g) search for the letters "ain" (/ain) in a string, and display the matches.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var str = "The rain in SPAIN stays mainly in the plain"; var res = str.match(/ain/g); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
15.9 替换字符串中的字符-replace()
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Please visit Microsoft!</p> <script> function myFunction() { let text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.replace("Microsoft","W3Schools"); } </script> </body> </html>
15.10 将字符串转换为大写-toUpperCase()
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Convert string to upper case:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Hello World!</p> <script> function myFunction() { let text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toUpperCase(); } </script> </body> </html>
15.11 将字符串转换为小写-toLowerCase()
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Convert string to lower case:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Hello World!</p> <script> function myFunction() { let text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.toLowerCase(); } </script> </body> </html>
15.12 将字符串拆分为数组-split()
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Display the first array element, after a string split:</p> <p id="demo"></p> <script> let text = "a,b,c,d,e,f"; const myArray = text.split(","); document.getElementById("demo").innerHTML = myArray[0]; </script> </body> </html>
十六. JavaScript数字(numbers)
16.1 数字可以写成带小数或不带小数
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Numbers can be written with or without decimals:</p> <p id="demo"></p> <script> let x = 3.14; let y = 3; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>
16.2 特大或特小数字可以用指数表示法书写
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Extra large or extra small numbers can be written with scientific (exponent) notation:</p> <p id="demo"></p> <script> let x = 123e5; let y = 123e-5; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>
16.3 数字被认为是准确的,最多只有15位数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Integers (numbers without a period or exponent notation) are accurate up to 15 digits:</p> <p id="demo"></p> <script> let x = 999999999999999; let y = 9999999999999999; document.getElementById("demo").innerHTML = x + "<br>" + y; </script> </body> </html>
16.4 浮点运算并不总是100%准确
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Floating point arithmetic is not always 100% accurate.</p> <p id="demo"></p> <script> let x = 0.2 + 0.1; document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x; </script> </body> </html>
16.5 但它有助于乘以和除以10
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Floating point arithmetic is not always 100% accurate:</p> <p id="demo1"></p> <p>But it helps to multiply and divide:</p> <p id="demo2"></p> <script> let x = 0.2 + 0.1; document.getElementById("demo1").innerHTML = "0.2 + 0.1 = " + x; let y = (0.2*10 + 0.1*10) / 10; document.getElementById("demo2").innerHTML = "0.2 + 0.1 = " + y; </script> </body> </html>
16.6 添加两个数字会产生一个新数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>If you add two numbers, the result will be a number:</p> <p id="demo"></p> <script> let x = 10; let y = 20; let z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.7 添加两个数字字符串会产生一个连接的字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>If you add two numeric strings, the result will be a concatenated string:</p> <p id="demo"></p> <script> let x = "10"; let y = "20"; let z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.8 添加数字和数字字符串也会导致连接字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>If you add a number and a numeric string, the result will be a concatenated string:</p> <p id="demo"></p> <script> let x = 10; let y = "20"; let z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.9 添加字符串和数字时的常见错误 1
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>A common mistake is to expect this result to be 30:</p> <p id="demo"></p> <script> var x = 10; var y = 20; document.getElementById("demo").innerHTML = "The result is: " + x + y; </script> </body> </html>
16.10 添加字符串和数字时的常见错误 2
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>A common mistake is to expect this result to be 102030:</p> <p id="demo"></p> <script> let x = 10; let y = 20; let z = "30"; let result = x + y + z; document.getElementById("demo").innerHTML = result; </script> </body> </html>
16.11 JavaScript在除法时会尝试将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>JavaScript will try to convert strings to numbers when dividing:</p> <p id="demo"></p> <script> let x = "100"; let y = "10"; let z = x / y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.12 JavaScript会在乘法时尝试将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>JavaScript will try to convert strings to numbers when dividing:</p> <p id="demo"></p> <script> let x = "100"; let y = "10"; let z = x / y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.13 JavaScript会在减法时尝试将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>JavaScript will try to convert strings to numbers when subtracting:</p> <p id="demo"></p> <script> let x = "100"; let y = "10"; let z = x - y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.14 添加时 JavaScript不会将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>JavaScript will NOT convert strings to numbers when adding:</p> <p id="demo"></p> <script> let x = "100"; let y = "10"; let z = x + y; document.getElementById("demo").innerHTML = z; </script> </body> </html>
16.15 一个数字除以一个字符串是NaN(不是数字)
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>A number divided by a non-numeric string becomes NaN (Not a Number):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 100 / "Apple"; </script> </body> </html>
16.16 一个数字除以一个数字字符串是一个数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>A number divided by a numeric string becomes a number:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 100 / "10"; </script> </body> </html>
16.17 如果值是数字,则全局JavaScript函数isNaN() 返回
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>You can use the global JavaScript function isNaN() to find out if a value is not a number:</p> <p id="demo"></p> <script> let x = 100 / "Apple"; document.getElementById("demo").innerHTML = isNaN(x); </script> </body> </html>
16.18 在数学运算中使用NaN将始终返回NaN
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>If you use NaN in a mathematical operation, the result will also be NaN:</p> <p id="demo"></p> <script> let x = NaN; let y = 5; document.getElementById("demo").innerHTML = x + y; </script> </body> </html>
16.19 在数学字符串运算中使用NaN将连接NaN
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>If you use NaN in a mathematical operation, the result can be a concatenation:</p> <p id="demo"></p> <script> let x = NaN; let y = "5"; document.getElementById("demo").innerHTML = x + y; </script> </body> </html>
16.20 NaN(Not a Number)是一个数字 (是的!typeof 返回number)
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>The typeof NaN is number:</p> <p id="demo"></p> <script> let x = NaN; document.getElementById("demo").innerHTML = typeof x; </script> </body> </html>
16.21 如果您计算的数字超出可能的最大数字,则返回无穷大
16.22 除以零也会产生无穷大
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Infinity is returned if you calculate a number outside the largest possible number:</p> <p id="demo"></p> <script> let myNumber = 2; let txt = ""; while (myNumber != Infinity) { myNumber = myNumber * myNumber; txt = txt + myNumber + "<br>"; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>
16.23 Infinity 是一个数字(typeof Ininity 返回number)
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>The typeof NaN is number:</p> <p id="demo"></p> <script> let x = NaN; document.getElementById("demo").innerHTML = typeof x; </script> </body> </html>
16.24 以 0x开头的常量被解释为十六进制
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</p> <p id="demo"></p> <script> let x = 0xFF; document.getElementById("demo").innerHTML = "0xFF = " + x; </script> </body> </html>
16.25 toString()方法可以将数字输出为十六进制、八进制、和二进制
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>The toString() method can output numbers from base 2 to 36:</p> <p id="demo"></p> <script> let myNumber = 32; document.getElementById("demo").innerHTML = "32 = " + "<br>" + " Decimal " + myNumber.toString(10) + "<br>" + " Hexadecimal " + myNumber.toString(16) + "<br>" + " Octal " + myNumber.toString(8) + "<br>" + " Binary " + myNumber.toString(2); </script> </body> </html>
16.26 number可以是对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p id="demo"></p> <script> // x is a number let x = 123; // y is a Number object let y = new Number(123); document.getElementById("demo").innerHTML = typeof x + "<br>" + typeof y; </script> </body> </html>
16.27 无法安全地比较number和object
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>Numbers and Number objects cannot be safely compared:</p> <p id="demo"></p> <script> // x is a number let x = 500; // y is an object let y = new Number(500); document.getElementById("demo").innerHTML = (x===y); </script> </body> </html>
16.28 无法安全地比较object和object
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>JavaScript objects cannot be compared:</p> <p id="demo"></p> <script> // x is an object let x = new Number(500); // y is an object let y = new Number(500); document.getElementById("demo").innerHTML = (x==y); </script> </body> </html>
十七. JavaScript数字方法
17.1 toString()方法将数字转换为字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>The toString() method can output numbers from base 2 to 36:</p> <p id="demo"></p> <script> let myNumber = 32; document.getElementById("demo").innerHTML = "32 = " + "<br>" + " Decimal " + myNumber.toString(10) + "<br>" + " Hexadecimal " + myNumber.toString(16) + "<br>" + " Octal " + myNumber.toString(8) + "<br>" + " Binary " + myNumber.toString(2); </script> </body> </html>
17.2 valueOf()方法将数字作为数字返回
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Methods</h2> <p>The valueOf() method returns a number as a number:</p> <p id="demo"></p> <script> let x = 123; document.getElementById("demo").innerHTML = x.valueOf() + "<br>" + (123).valueOf() + "<br>" + (100 + 23).valueOf(); </script> </body> </html>
17.3 toExponential()返回一个带有指数符号的数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Methods</h2> <p>The toExponential() method returns a string, with the number rounded and written using exponential notation.</p> <p>An optional parameter defines the number of digits behind the decimal point.</p> <p id="demo"></p> <script> let x = 9.656; document.getElementById("demo").innerHTML = x.toExponential() + "<br>" + x.toExponential(2) + "<br>" + x.toExponential(4) + "<br>" + x.toExponential(6); </script> </body> </html>
17.4 toFixed()方法将数字四舍五入为位数
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Methods</h2> <p>The toFixed() method rounds a number to a given number of digits.</p> <p>For working with money, toFixed(2) is perfect.</p> <p id="demo"></p> <script> let x = 9.656; document.getElementById("demo").innerHTML = x.toFixed(0) + "<br>" + x.toFixed(2) + "<br>" + x.toFixed(4) + "<br>" + x.toFixed(6); </script> </body> </html>
17.5 toPrecision()方法以指定的长度写入的数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Methods</h2> <p>The toPrecision() method returns a string, with a number written with a specified length:</p> <p id="demo"></p> <script> let x = 9.656; document.getElementById("demo").innerHTML = x.toPrecision() + "<br>" + x.toPrecision(2) + "<br>" + x.toPrecision(4) + "<br>" + x.toPrecision(6); </script> </body> </html>
17.6 全部方法Number()将变量转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Global Methods</h2> <p>The Number() method converts variables to numbers:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Number(true) + "<br>" + Number(false) + "<br>" + Number("10") + "<br>" + Number(" 10") + "<br>" + Number("10 ") + "<br>" + Number(" 10 ") + "<br>" + Number("10.33") + "<br>" + Number("10,33") + "<br>" + Number("10 33") + "<br>" + Number("John"); </script> </body> </html>
17.8 全局方法parseInter()将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Global Functions</h2> <h2>parseInt()</h2> <p>The global JavaScript function parseInt() converts strings to numbers:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = parseInt("-10") + "<br>" + parseInt("-10.33") + "<br>" + parseInt("10") + "<br>" + parseInt("10.33") + "<br>" + parseInt("10 6") + "<br>" + parseInt("10 years") + "<br>" + parseInt("years 10"); </script> </body> </html>
17.9 全局方法parseFloat()将字符串转换为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Global Methods</h2> <p>The parseFloat() method converts strings to numbers:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = parseFloat("10") + "<br>" + parseFloat("10.33") + "<br>" + parseFloat("10 6") + "<br>" + parseFloat("10 years") + "<br>" + parseFloat("years 10"); </script> </body> </html>
17.10 MAX_VALUE返回JavaScript中可能的最大数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>MAX_VALUE returns the largest possible number in JavaScript.</p> <p id="demo"></p> <script> let x = Number.MAX_VALUE; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.11 MIN_VALUE返回JavaScript中可能的最小数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>MIN_VALUE returns the smallest number possible in JavaScript.</p> <p id="demo"></p> <script> let x = Number.MIN_VALUE; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.12 POSITVE_INFINITY代表无穷大
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>POSITIVE_INFINITY</p> <p id="demo"></p> <script> let x = Number.POSITIVE_INFINITY; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.13 POSITIVE_INFINITY在溢出时返回
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>POSITIVE_INFINITY is returned on overflow:</p> <p id="demo"></p> <script> let x = 1 / 0; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.14 NEGATIVE_INFINITY表示负无穷大
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>NEGATIVE_INFINITY</p> <p id="demo"></p> <script> let x = Number.NEGATIVE_INFINITY; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.15 溢出时返回NEGATIVE_INFINITY
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>NEGATIVE_INFINITY</p> <p id="demo"></p> <script> let x = -1 / 0; document.getElementById("demo").innerHTML = x; </script> </body> </html>
17.16 NaN表示"非数字"
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Number.NaN; </script> </body> </html>
17.17 对字符串执行的算法运算将导致NaN
<!DOCTYPE html> <html> <body> <h2>JavaScript Numbers</h2> <p>A number divided by a non-numeric string becomes NaN (Not a Number):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 100 / "Apple"; </script> </body> </html>
17.18 在变量上使用Number属性将返回undefined
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Properties</h2> <p>Using a Number property on a variable, expression, or value, will return undefined:</p> <p id="demo"></p> <script> let x = 6; document.getElementById("demo").innerHTML = x.MAX_VALUE; </script> </body> </html>
十八. JavaScript数学(Maths)
18.1 Math.PI返回PI的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.PI</h2> <p>Math.PI returns the ratio of a circle's circumference to its diameter:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.PI; </script> </body> </html>
18.2 Math.round(x)返回x的舍入值
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.round()</h2> <p>Math.round(x) returns the value of x rounded to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.round(4.5); </script> </body> </html>
18.3 Math.pow(x,y)返回x的y次幂
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.pow()</h2> <p>Math.pow(x,y) returns the value of x to the power of y:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.pow(8,2); </script> </body> </html>
18.4 Math.sqrt(x)返回x的平方根
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.sqrt()</h2> <p>Math.sqrt(x) returns the square root of x:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.sqrt(64); </script> </body> </html>
18.5 Math.abs(x)返回x的绝对值(正)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.abs()</h2> <p>Math.abs(x) returns the absolute (positive) value of x:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.abs(-4.4); </script> </body> </html>
18.6 Math.ceil(x)返回四舍五入的x值
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.ceil()</h2> <p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.ceil(4.4); </script> </body> </html>
18.7 Math.floor(x)返回向下舍入的x值
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.floor()</h2> <p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(4.7); </script> </body> </html>
18.8 Math.sin(x)返回角度x的正弦值(以弧度表示)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.sin()</h2> <p>Math.sin(x) returns the sin of x (given in radians):</p> <p>Angle in radians = (angle in degrees) * PI / 180.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180); </script> </body> </html>
18.9 Math.cos(x)返回角度x的余弦值(以弧度表示)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.cos()</h2> <p>Math.cos(x) returns the cosine of x (given in radians):</p> <p>Angle in radians = (angle in degrees) * PI / 180.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180); </script> </body> </html>
18.10 Math.max()从参数列表中返回具有最大的数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.max()</h2> <p>Math.max() returns the highest value in a list of arguments.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.max(0, 150, 30, 20, -8, -200); </script> </body> </html>
18.11 Math.min()从参数列表中返回具有最小值的数字
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.min()</h2> <p>Math.min() returns the lowest value in a list of arguments:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.min(0, 150, 30, 20, -8, -200); </script> </body> </html>
18.12 将摄氏度转换为华氏度
<!DOCTYPE html> <html> <body> <h2>JavaScript Celcius to Fahrenhet</h2> <p>Insert a number into one of the input fields below:</p> <p><input id="c" onkeyup="convert('C')"> degrees Celsius</p> <p><input id="f" onkeyup="convert('F')"> degrees Fahrenheit</p> <p>Note that the <b>Math.round()</b> method is used, so that the result will be returned as an integer.</p> <script> function convert(degree) { var x; if (degree == "C") { x = document.getElementById("c").value * 9 / 5 + 32; document.getElementById("f").value = Math.round(x); } else { x = (document.getElementById("f").value -32) * 5 / 9; document.getElementById("c").value = Math.round(x); } } </script> </body> </html>
十九. JavaScript 随机(Random)
Math.random()返回一个介于0(包括)和1(不包括)之间的随机数
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.random()</h2> <p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.random(); </script> </body> </html>
如何返回0到9之间的随机整数(均包含在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 10); </script> </body> </html>
如何返回0到10之间的随机整数(均包含在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor(Math.random() * 11) returns a random integer between 0 and 10 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 11); </script> </body> </html>
如何返回0到99之间的随机整数(均包含在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 100); </script> </body> </html>
如何返回0到100之间的随机整数(均包含在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor() used with Math.random() * 101 returns a random integer between 0 and 100 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 101); </script> </body> </html>
如何返回1到100之间的随机整数(均包含在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor(Math.random() * 100) + 1) returns a random integer between 1 and 100 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 100) + 1; </script> </body> </html>
如何返回x(包括)和y(不包括)之间的随机整数
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.random()</h2> <p>Every time you click the button, getRndInteger(min, max) returns a random number between 0 and 9 (both included):</p> <button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button> <p id="demo"></p> <script> function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min)) + min; } </script> </body> </html>
如何返回x和y之间的随机整数(均包括在内)
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.random()</h2> <p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p> <button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Click Me</button> <p id="demo"></p> <script> function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; } </script> </body> </html>
二十. JavaScript日期(Dates)
20.1 使用Date()显示今天的日期和时间
<!DOCTYPE html> <html> <body> <h2>JavaScript new Date()</h2> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d; </script> </body> </html>
20.2 使用getFullYear()显示年份
<!DOCTYPE html> <html> <body> <h2>JavaScript getFullYear()</h2> <p>The getFullYear() method returns the full year of a date:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); </script> </body> </html>
20.3 使用getTime()计算自1970年以来的毫秒数
<!DOCTYPE html> <html> <body> <h2>JavaScript getTime()</h2> <p>The internal clock in JavaScript counts from midnight January 1, 1970.</p> <p>The getTime() function returns the number of milliseconds since then:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getTime(); </script> </body> </html>
20.4 使用setFullYear()设置特定日期
<!DOCTYPE html> <html> <body> <h2>JavaScript setFullYear()</h2> <p>The setFullYear() method sets the year of a date object:</p> <p id="demo"></p> <script> const d = new Date(); d.setFullYear(2020); document.getElementById("demo").innerHTML = d; </script> </body> </html>
20.5 使用toUTCString()将今天的日期(根据UTC)转换为字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Date()</h2> <p>The toUTCString() method converts a date to a UTC string (a date display standard):</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString(); </script> </body> </html>
20.6 使用getDay()将工作日显示为数字
<!DOCTYPE html> <html> <body> <h2>JavaScript getDay()</h2> <p>The getDay() method returns the weekday as a number:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getDay(); </script> </body> </html>
20.7 使用getDay()和数组将工作日显示为名称
<!DOCTYPE html> <html> <body> <h2>JavaScript getDay()</h2> <p>The getDay() method returns the weekday as a number.</p> <p>You can use an array to display the name of the weekday:</p> <p id="demo"></p> <script> const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; const d = new Date(); let day = days[d.getDay()]; document.getElementById("demo").innerHTML = day; </script> </body> </html>
20.8 显示时钟
<!DOCTYPE html> <html> <body onload="startTime()"> <h2>JavaScript Clock</h2> <div id="txt"></div> <script> function startTime() { const today = new Date(); let h = today.getHours(); let m = today.getMinutes(); let s = today.getSeconds(); m = checkTime(m); s = checkTime(s); document.getElementById('txt').innerHTML = h + ":" + m + ":" + s; setTimeout(startTime, 1000); } function checkTime(i) { if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10 return i; } </script> </body> </html>
二十一. JavaScript数组(Arrays)
21.1 创建一个数组 1
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
21.2 创建数组 2
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const cars = [ "Saab", "Volvo", "BMW" ]; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
21.3 访问数组元素
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars[0]; </script> </body> </html>
21.4 更改数组元素
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <p>Array elements are accessed using their index number:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits[0] = "Kiwi"; document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
21.5 访问一个完整的数组
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
21.6 查找数组的长度
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>The length property returns the length of an array.</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.length; </script> </body> </html>
21.7 循环遍历数组
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>The best way to loop through an array is using a standard for loop:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fLen = fruits.length; let text = "<ul>"; for (let i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>"; document.getElementById("demo").innerHTML = text; </script> </body> </html>
21.8 向数组添加一个元素
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>The length property provides an easy way to append new elements to an array without using the push() method.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple"]; document.getElementById("demo").innerHTML = fruits; function myFunction() { fruits[fruits.length] = "Lemon"; document.getElementById("demo").innerHTML = fruits; } </script> </body> </html>
21.9 将未定义的“hloes”添加到数组
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>Adding elements with high indexes can create undefined "holes" in an array.</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple"]; fruits[6] = "Lemon"; let fLen = fruits.length; let text = ""; for (i = 0; i < fLen; i++) { text += fruits[i] + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
21.10 如何识别数组 1
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>The instanceof operator returns true when used on an array:</p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple"]; document.getElementById("demo").innerHTML = fruits instanceof Array; </script> </body> </html>
21.11 如何识别数组 2
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple"]; document.getElementById("demo").innerHTML = Array.isArray(fruits); </script> </body> </html>
二十二. JavaScript数组方法(Array Methods)
22.1 向数组中添加一个元素
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>push()</h2> <p>The push() method appends a new element to an array:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.push("Kiwi"); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
22.2 删除数组的最后一个元素-pop()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>pop()</h2> <p>The pop() method removes the last element from an array.</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.pop(); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
22.3 将数组的所有元素连接成一个字符串-join()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>join()</h2> <p>The join() method joins array elements into a string.</p> <p>It this example we have used " * " as a separator between the elements:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); </script> </body> </html>
22.4 加入两个数组-concat()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>concat()</h2> <p>The concat() method merges (concatenates) arrays:</p> <p id="demo"></p> <script> const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; const myChildren = myGirls.concat(myBoys); document.getElementById("demo").innerHTML = myChildren; </script> </body> </html>
22.5 加入三个数组-concat()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>concat()</h2> <p>The concat() method merges (concatenates) arrays:</p> <p id="demo"></p> <script> const array1 = ["Cecilie", "Lone"]; const array2 = ["Emil", "Tobias", "Linus"]; const array3 = ["Robin", "Morgan"]; const myChildren = array1.concat(array2, array3); document.getElementById("demo").innerHTML = myChildren; </script> </body> </html>
22.6 将元素添加到数组中的位置2-splice()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>splice()</h2> <p>The splice() method adds new elements to an array:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.splice(2, 0, "Lemon", "Kiwi"); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
22.7 将数组转换为字符串-toString()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>toString()</h2> <p>The toString() method returns an array as a comma separated string:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); </script> </body> </html>
22.8 将新元素添加到数组的开头-unshift()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>unshift()</h2> <p>The unshift() method adds new elements to the beginning of an array:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.unshift("Lemon"); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
22.9 删除数组的第一个元素-shift()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>shift()</h2> <p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.shift(); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
22.10 从数组中选择元素-slice()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Methods</h2> <h2>slice()</h2> <p>When the slice() method is given two arguments, it selects array elements from the start argument, and up to (but not included) the end argument:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(1,3); document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus; </script> </body> </html>
二十三. JavaScript数组排序(Array Sort)
23.1 按升序对数组进行排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The sort() method sorts an array alphabetically:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; fruits.sort(); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
23.2 按降序对数组进行排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort Reverse</h2> <p>The reverse() method reverses the elements in an array.</p> <p>By combining sort() and reverse() you can sort an array in descending order:</p> <p id="demo1"></p> <p id="demo2"></p> <script> // Create and display an array: const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo1").innerHTML = fruits; // First sort the array fruits.sort(); // Then reverse it: fruits.reverse(); document.getElementById("demo2").innerHTML = fruits; </script> </body> </html>
23.3 对数字数组进行升序排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Sort the array in ascending order:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo1").innerHTML = points; points.sort(function(a, b){return a - b}); document.getElementById("demo2").innerHTML = points; </script> </body> </html>
23.4 对数字数组进行降序排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Sort the array in descending order:</p> <p id="demo1"></p> <p id="demo2"></p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo1").innerHTML = points; points.sort(function(a, b){return b - a}); document.getElementById("demo2").innerHTML = points; </script> </body> </html>
23.5 对数字进行排序(按字母顺序或数字)
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Click the buttons to sort the array alphabetically or numerically.</p> <button onclick="myFunction1()">Sort Alphabetically</button> <button onclick="myFunction2()">Sort Numerically</button> <p id="demo"></p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction1() { points.sort(); document.getElementById("demo").innerHTML = points; } function myFunction2() { points.sort(function(a, b){return a - b}); document.getElementById("demo").innerHTML = points; } </script> </body> </html>
23.6 以随机对数组编号进行排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Click the button (again and again) to sort the array in random order.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = points; function myFunction() { points.sort(function(a, b){return 0.5 - Math.random()}); document.getElementById("demo").innerHTML = points; } </script> </body> </html>
23.7 查找数组中的最大数
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The highest number is <span id="demo"></span>.</p> <script> const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b-a}); document.getElementById("demo").innerHTML = points[0]; </script> </body> </html>
23.8 使用Math.min()查找数组中的最小数
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The lowest number is <span id="demo"></span>.</p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = myArrayMin(points); function myArrayMin(arr) { return Math.min.apply(null, arr); } </script> </body> </html>
23.9 使用Math.max()查找数组中的最大数
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The highest number is <span id="demo"></span>.</p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = myArrayMax(points); function myArrayMax(arr) { return Math.max.apply(null, arr); } </script> </body> </html>
23.10 使用“自制”myArrayMin方法
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The lowest number is <span id="demo"></span>.</p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = myArrayMin(points); function myArrayMin(arr) { let len = arr.length; let min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min; } </script> </body> </html>
23.11 使用"自制"myArrayMax方法
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>The highest number is <span id="demo"></span>.</p> <script> const points = [40, 100, 1, 5, 25, 10]; document.getElementById("demo").innerHTML = myArrayMax(points); function myArrayMax(arr) { let len = arr.length; let max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max; } </script> </body> </html>
23.12 按数字属性对对象进行排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Sort car objects on age:</p> <p id="demo"></p> <script> const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; displayCars(); cars.sort(function(a, b){return a.year - b.year}); displayCars(); function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; } </script> </body> </html>
23.13 按字符串属性对对象进行排序
<!DOCTYPE html> <html> <body> <h2>JavaScript Array Sort</h2> <p>Click the buttons to sort car objects on type.</p> <button onclick="myFunction()">Sort</button> <p id="demo"></p> <script> const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; displayCars(); function myFunction() { cars.sort(function(a, b){ let x = a.type.toLowerCase(); let y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; }); displayCars(); } function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; } </script> </body> </html>
二十四. JavaScript数组迭代(Array Lteration)
24.1 Array.forEach()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.forEach()</h2> <p>Calls a function once for each array element.</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); document.getElementById("demo").innerHTML = txt; function myFunction(value, index, array) { txt += value + "<br>"; } </script> </body> </html>
24.2 Array.map()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.map()</h2> <p>Creates a new array by performing a function on each array element.</p> <p id="demo"></p> <script> const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction); document.getElementById("demo").innerHTML = numbers2; function myFunction(value, index, array) { return value * 2; } </script> </body> </html>
24.3 Array.filter()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.filter()</h2> <p>Creates a new array with all array elements that passes a test.</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); document.getElementById("demo").innerHTML = over18; function myFunction(value, index, array) { return value > 18; } </script> </body> </html>
24.4 Array.reduce()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.reduce()</h2> <p>This example finds the sum of all numbers in an array:</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); document.getElementById("demo").innerHTML = "The sum is " + sum; function myFunction(total, value, index, array) { return total + value; } </script> </body> </html>
24.5 Array.reduceRight()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.reduceRight()</h2> <p>This example finds the sum of all numbers in an array:</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); document.getElementById("demo").innerHTML = "The sum is " + sum; function myFunction(total, value, index, array) { return total + value; } </script> </body> </html>
24.6 Array.every()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.every()</h2> <p>The every() method checks if all array values pass a test.</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let allOver18 = numbers.every(myFunction); document.getElementById("demo").innerHTML = "All over 18 is " + allOver18; function myFunction(value, index, array) { return value > 18; } </script> </body> </html>
24.7 Array.some()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.some()</h2> <p>The some() method checks if some array values pass a test.</p> <p id="demo"></p> <script> const numbers = [45, 4, 9, 16, 25]; let someOver18 = numbers.some(myFunction); document.getElementById("demo").innerHTML = "Some over 18 is " + someOver18; function myFunction(value, index, array) { return value > 18; } </script> </body> </html>
24.8 Array.indexOf()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.indexOf()</h2> <p id="demo"></p> <script> const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position = fruits.indexOf("Apple") + 1; document.getElementById("demo").innerHTML = "Apple is found in position " + position; </script> </body> </html>
24.9 Array.lastIndexOf()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.lastIndexOf()</h2> <p id="demo"></p> <script> const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position = fruits.lastIndexOf("Apple") + 1; document.getElementById("demo").innerHTML = "Apple is found in position " + position; </script> </body> </html>
24.10 Array.find()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.find()</h2> <p id="demo"></p> <script> const numbers = [4, 9, 16, 25, 29]; let first = numbers.find(myFunction); document.getElementById("demo").innerHTML = "First number over 18 is " + first; function myFunction(value, index, array) { return value > 18; } </script> </body> </html>
24.11 Array.findIndex()
<!DOCTYPE html> <html> <body> <h2>JavaScript Array.findIndex()</h2> <p id="demo"></p> <script> const numbers = [4, 9, 16, 25, 29]; document.getElementById("demo").innerHTML = "First number over 18 has index " + numbers.findIndex(myFunction); function myFunction(value, index, array) { return value > 18; } </script> </body> </html>
二十五. JavaScript类型转换(Type Conversion)
25.1 显示所有变量类型的类型
<!DOCTYPE html> <html> <body> <h2>The JavaScript typeof Operator</h2> <p>The typeof operator returns the type of a variable, object, function or expression.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = typeof "john" + "<br>" + typeof 3.14 + "<br>" + typeof NaN + "<br>" + typeof false + "<br>" + typeof [1,2,3,4] + "<br>" + typeof {name:'john', age:34} + "<br>" + typeof new Date() + "<br>" + typeof function () {} + "<br>" + typeof myCar + "<br>" + typeof null; </script> </body> </html>
25.2 显示所有变量的数据结构
<!DOCTYPE html> <html> <body> <h2>The JavaScript constructor Property</h2> <p>The constructor property returns the constructor function for a variable or an object.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "john".constructor + "<br>" + (3.14).constructor + "<br>" + false.constructor + "<br>" + [1,2,3,4].constructor + "<br>" + {name:'john', age:34}.constructor + "<br>" + new Date().constructor + "<br>" + function () {}.constructor; </script> </body> </html>
25.3 使用String()将数字转换为字符串
<!DOCTYPE html> <html> <body> <h2>The JavaScript String() Method</h2> <p>The String() method can convert a number to a string.</p> <p id="demo"></p> <script> let x = 123; document.getElementById("demo").innerHTML = String(x) + "<br>" + String(123) + "<br>" + String(100 + 23); </script> </body> </html>
25.4 使用toString()将数字转换为字符串
<!DOCTYPE html> <html> <body> <h2>JavaScript Number Methods</h2> <p>The toString() method converts a number to a string.</p> <p id="demo"></p> <script> let x = 123; document.getElementById("demo").innerHTML = x.toString() + "<br>" + (123).toString() + "<br>" + (100 + 23).toString(); </script> </body> </html>
25.5 判断变量是否为数组
<!DOCTYPE html> <html> <body> <h2>JavaScript Arrays</h2> <p>This "home made" isArray() function returns true when used on an array:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple"]; document.getElementById("demo").innerHTML = isArray(fruits); function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } </script> </body> </html>
25.6 找出变量是否为日期
<!DOCTYPE html> <html> <body> <h2>JavaScript Date Object</h2> <p>This "home made" isDate() function returns true when used on an date:</p> <p id="demo"></p> <script> const myDate = new Date(); document.getElementById("demo").innerHTML = isDate(myDate); function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; } </script> </body> </html>
二十六. JavaScript布尔值(Booleans)
26.1 显示Boolean(10>9)
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the value of Boolean(10 > 9):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Boolean(10 > 9); </script> </body> </html>
26.2 显示10>9的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the value of 10 > 9:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 10 > 9; </script> </body> </html>
26.3 一切有实际价值的东西都是真的
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "100 is " + Boolean(100) + "<br>" + "3.14 is " + Boolean(3.14) + "<br>" + "-15 is " + Boolean(-15) + "<br>" + "Any (not empty) string is " + Boolean("Hello") + "<br>" + "Even the string 'false' is " + Boolean('false') + "<br>" + "Any expression (except zero) is " + Boolean(1 + 7 + 3.14); </script> </body> </html>
26.4 布尔值零为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of 0:</p> <p id="demo"></p> <script> let x = 0; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
26.5 负零的布尔值是false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of -0:</p> <p id="demo"></p> <script> let x = -0; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
26.6 空字符串的布尔值为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of "":</p> <p id="demo"></p> <script> let x = ""; document.getElementById("demo").innerHTML = Boolean(""); </script> </body> </html>
26.7 undefined的布尔值为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of undefined:</p> <p id="demo"></p> <script> let x; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
26.8 null的布尔值为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of null:</p> <p id="demo"></p> <script> let x = null; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
26.9 false的布尔值为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of false:</p> <p id="demo"></p> <script> let x = false; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
26.10 NaN的布尔值为false
<!DOCTYPE html> <html> <body> <h2>JavaScript Booleans</h2> <p>Display the Boolean value of NaN:</p> <p id="demo"></p> <script> let x = 10 / "Hello"; document.getElementById("demo").innerHTML = Boolean(x); </script> </body> </html>
二十七. JavaScript比较(Comparisons)
27.1 将5赋值给x,并显示(x==8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x == 8):</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x == 8); </script> </body> </html>
27.2 将5赋值给x,并显示(x==5)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x == 5):</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x == 5); </script> </body> </html>
27.3 将5赋值给x,并显示(x===5)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x === 5):</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x === 5); </script> </body> </html>
27.4 将5赋值给x,并显示(x===“5”)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x === "5").</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x === "5"); </script> </body> </html>
27.5 将5赋值给x,并显示(x != 8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x != 8).</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x != 8); </script> </body> </html>
27.6 将5赋值给x,并显示(x !== 5)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x !== 5):</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x !== 5); </script> </body> </html>
27.8 将5赋值给x,并显示(x !== "5")的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x !== "5"); </script> </body> </html>
27.9 将5赋值给x,并显示(x>8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x > 8).</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x > 8); </script> </body> </html>
27.10 将5赋值给x,并显示(x<8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x < 8).</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x < 8); </script> </body> </html>
27.11 将5赋值给x,并显示(x>=8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x >= 8).</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x >= 8); </script> </body> </html>
27.12 将5赋值给x,并显示(x<=8)的值
<!DOCTYPE html> <html> <body> <h2>JavaScript Comparison</h2> <p>Assign 5 to x, and display the value of the comparison (x <= 8).</p> <p id="demo"></p> <script> let x = 5; document.getElementById("demo").innerHTML = (x <= 8); </script> </body> </html>
二十八. JavaScript 条件(Conditionals)
28.1 if语句
<!DOCTYPE html> <html> <body> <h2>JavaScript if</h2> <p>Display "Good day!" if the hour is less than 18:00:</p> <p id="demo">Good Evening!</p> <script> if (new Date().getHours() < 18) { document.getElementById("demo").innerHTML = "Good day!"; } </script> </body> </html>
28.2 else语句
<!DOCTYPE html> <html> <body> <h2>JavaScript if .. else</h2> <p>A time-based greeting:</p> <p id="demo"></p> <script> const hour = new Date().getHours(); let greeting; if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; } document.getElementById("demo").innerHTML = greeting; </script> </body> </html>
28.3 else if 语句
<!DOCTYPE html> <html> <body> <h2>JavaScript if .. else</h2> <p>A time-based greeting:</p> <p id="demo"></p> <script> const time = new Date().getHours(); let greeting; if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; } document.getElementById("demo").innerHTML = greeting; </script> </body> </html>
28.4 随机链接
<!DOCTYPE html> <html> <body> <h2>JavaScript Math.random()</h2> <p id="demo"></p> <script> let text; if (Math.random() < 0.5) { text = "<a href='https://w3schools.com'>Visit W3Schools</a>"; } else { text = "<a href='https://wwf.org'>Visit WWF</a>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
28.5 切换语句
<!DOCTYPE html> <html> <body> <h2>JavaScript switch</h2> <p id="demo"></p> <script> let day; switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; } document.getElementById("demo").innerHTML = "Today is " + day; </script> </body> </html>
二十九. JavaScript循环(Loops)
29.1 循环
<!DOCTYPE html> <html> <body> <h2>JavaScript For Loop</h2> <p id="demo"></p> <script> let text = ""; for (let i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.2 循环数组
<!DOCTYPE html> <html> <body> <h2>JavaScript For Loop</h2> <p id="demo"></p> <script> const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"]; let text = ""; for (let i = 0; i < cars.length; i++) { text += cars[i] + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.3 循环遍历HTML headers
<!DOCTYPE html> <html> <body> <h2>JavaScript For Loop</h2> <p>Loop from 1 to 6, to make HTML headings.</p> <div id="demo"></div> <script> var x ="", i; for (i=1; i<=6; i++) { x = x + "<h" + i + ">Heading " + i + "</h" + i + ">"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
29.4 While循环
<!DOCTYPE html> <html> <body> <h2>JavaScript While Loop</h2> <p id="demo"></p> <script> let text = ""; let i = 0; while (i < 10) { text += "<br>The number is " + i; i++; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.5 执行do While循环
<!DOCTYPE html> <html> <body> <h2>JavaScript Do While Loop</h2> <p id="demo"></p> <script> let text = "" let i = 0; do { text += "<br>The number is " + i; i++; } while (i < 10); document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.6 Break 循环
<!DOCTYPE html> <html> <body> <h2>JavaScript Loops</h2> <p>A loop with a <b>break</b> statement.</p> <p id="demo"></p> <script> let text = ""; for (let i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.7 Break 和 continue 循环
<!DOCTYPE html> <html> <body> <h2>JavaScript Loops</h2> <p>A loop with a <b>continue</b> statement.</p> <p>A loop which will skip the step where i = 3.</p> <p id="demo"></p> <script> let text = ""; for (let i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
29.8 使用for...in 语句循环遍历对象的元素
<!DOCTYPE html> <html> <body> <h2>JavaScript For In Loop</h2> <p>The for in statement loops through the properties of an object:</p> <p id="demo"></p> <script> const person = {fname:"John", lname:"Doe", age:25}; let txt = ""; for (let x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>
三十. JavaScript错误处理(Error Handling)
30.1 try...catch语句
<!DOCTYPE html> <html> <body> <h2>JavaScript Error Handling</h2> <p>How to use <b>catch</b> to display an error.</p> <p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script> </body> </html>
30.2 带有确认框的try...catch语句
<!DOCTYPE html> <html> <script> var txt = ""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt = "There was an error on this page.\n\n"; txt += "Click OK to continue viewing this page,\n"; txt += "or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href = "https://www.w3schools.com/"; } } } </script> <body> <h2>JavaScript Error Handling</h2> <input type="button" value="View message" onclick="message()" /> </body> </html>
30.3 错误事件
<!DOCTYPE html> <html> <head> <script> onerror = handleErr; var txt = ""; function handleErr(msg, url, l) { txt = "There was an error on this page.\n\n"; txt += "Error: " + msg + "\n"; txt += "URL: " + url + "\n"; txt += "Line: " + l + "\n\n"; txt += "Click OK to continue.\n\n"; alert(txt); return true; } function message() { adddlert("Welcome guest!"); } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>
三十一. JavaScript正则表达式(Regular Expressions)
31.1 在字符串中搜索表达式
<!DOCTYPE html> <html> <body> <h2>JavaScript Regular Expressions</h2> <p>Search a string for "w3Schools", and display the position of the match:</p> <p id="demo"></p> <script> let text = "Visit W3Schools!"; let n = text.search(/w3Schools/i); document.getElementById("demo").innerHTML = n; </script> </body> </html>
31.2 搜索表达式并替换它
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Please visit Microsoft!</p> <script> function myFunction() { let text = document.getElementById("demo").innerHTML; document.getElementById("demo").innerHTML = text.replace(/microsoft/i, "W3Schools"); } </script> </body> </html>
三十二. JavaScript对象(Objects)
32.1 创建JavaScript变量
<!DOCTYPE html> <html> <body> <h2>JavaScript Variables</h2> <p id="demo"></p> <script> // Create and display a variable: let person = "John Doe"; document.getElementById("demo").innerHTML = person; </script> </body> </html>
32.2 创建一个JavaScript对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>Creating an object:</p> <p id="demo"></p> <script> let person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; </script> </body> </html>
32.3 创建一个JavaScript对象(单行)
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>Creating a JavaScript Object:</p> <p id="demo"></p> <script> const person = {firstName:"John", lastName:"Doe", age:50,eyeColor:"blue"}; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
32.4 创建一个JavaScript对象(多行)
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>Creating a JavaScript Object:</p> <p id="demo"></p> <script> const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
32.5 使用new创建一个JavaScript对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>Creating a JavaScript Object:</p> <p id="demo"></p> <script> const person = new Object(); person.firstName = "John"; person.lastName = "Doe"; person.age = 50; person.eyeColor = "blue"; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
32.6 使用构造函数创建JavaScript对象
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Constructors</h2> <p id="demo"></p> <script> // Constructor function for Person objects function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } // Create a Person object const myFather = new Person("John", "Doe", 50, "blue"); // Display age document.getElementById("demo").innerHTML = "My father is " + myFather.age + "."; </script> </body> </html>
32.7 创建内置JavaScript对象
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x1 = new Object(); // A new Object object var x2 = new String(); // A new String object var x3 = new Number(); // A new Number object var x4 = new Boolean(); // A new Boolean object var x5 = new Array(); // A new Array object var x6 = new RegExp(); // A new RegExp object var x7 = new Function(); // A new Function object var x8 = new Date(); // A new Date object document.getElementById("demo").innerHTML = "x1: " + typeof x1 + "<br>" + "x2: " + typeof x2 + "<br>" + "x3: " + typeof x3 + "<br>" + "x4: " + typeof x4 + "<br>" + "x5: " + typeof x5 + "<br>" + "x6: " + typeof x6 + "<br>" + "x7: " + typeof x7 + "<br>" + "x8: " + typeof x8 + "<br>"; </script> <p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p> <p>Read the JavaScript tutorials.</p> </body> </html>
32.8 创建JavaScript变量的最佳方法
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x1 = {}; var x2 = ""; var x3 = 0; var x4 = false; var x5 = []; var x6 = /()/; var x7 = function(){}; document.getElementById("demo").innerHTML = "x1: " + typeof x1 + "<br>" + "x2: " + typeof x2 + "<br>" + "x3: " + typeof x3 + "<br>" + "x4: " + typeof x4 + "<br>" + "x5: " + typeof x5 + "<br>" + "x6: " + typeof x6 + "<br>" + "x7: " + typeof x7 + "<br>"; </script> </body> </html>
32.9 JavaScript对象是可变的
<!DOCTYPE html> <html> <body> <h2>JavaScript Objects</h2> <p>JavaScript objects are mutable.</p> <p>Any changes to a copy of an object will also change the original object:</p> <p id="demo"></p> <script> const person = { firstName: "John", lastName: "Doe", age:50, eyeColor: "blue" }; const x = person; x.age = 10; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
三十二. JavaScript对象属性(Object Properties)
32.1 使用 .property 访问
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Properties</h2> <p>Access a property with .property:</p> <p id="demo"></p> <script> const person = { firstname: "John", lastname: "Doe", age: 50, eyecolor: "blue" }; document.getElementById("demo").innerHTML = person.firstname + " is " + person.age + " years old."; </script> </body> </html>
32.2 使用 [property]访问属性
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Properties</h2> <p>Access a property with ["property"]:</p> <p id="demo"></p> <script> const person = { firstname: "John", lastname: "Doe", age: 50, eyecolor: "blue" }; document.getElementById("demo").innerHTML = person["firstname"] + " is " + person["age"] + " years old."; </script> </body> </html>
32.3 使用for in 访问
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Properties</h2> <p>Looping object property values:</p> <p id="demo"></p> <script> const person = { fname:"John", lname:"Doe", age:25 }; let txt = ""; for (let x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>
32.4 向现有对象添加新属性
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Properties</h2> <p>Add a new property to an existing object:</p> <p id="demo"></p> <script> const person = { firstname: "John", lastname: "Doe", age: 50, eyecolor: "blue" }; person.nationality = "English"; document.getElementById("demo").innerHTML = person.firstname + " is " + person.nationality + "."; </script> </body> </html>
32.5 从对象中删除属性
<!DOCTYPE html> <html> <body> <h2>JavaScript Object Properties</h2> <p>Deleting object properties.</p> <p id="demo"></p> <script> const person = { firstname: "John", lastname: "Doe", age: 50, eyecolor: "blue" }; delete person.age; document.getElementById("demo").innerHTML = person.firstname + " is " + person.age + " years old."; </script> </body> </html>
三十三. JSON对象(Objects)
33.1使用 .property访问属性
<!DOCTYPE html> <html> <body> <h2>Access a JavaScript Object</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "car":null}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name; </script> </body> </html>
33.2使用 [property]访问属性
<!DOCTYPE html> <html> <body> <h2>Access a JavaScript Object</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "car":null}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj["name"]; </script> </body> </html>
33.3循环遍历属性
<!DOCTYPE html> <html> <body> <h2>Looping Object Properties</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "car":null}'; const myObj = JSON.parse(myJSON); let text = ""; for (const x in myObj) { text += x + ", "; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
33.4循环遍历属性值
<!DOCTYPE html> <html> <body> <h2>Looping JavaScript Object Values</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "car":null}'; const myObj = JSON.parse(myJSON); let text = ""; for (const x in myObj) { text += myObj[x] + ", "; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
33.5访问嵌套的JSON对象
<!DOCTYPE html> <html> <body> <h2>Access Nested JavaScript Objects</h2> <p id="demo"></p> <script> const myObj = { "name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } document.getElementById("demo").innerHTML = myObj.cars.car2; </script> </body> </html>
33.6使用点符号修改值
<!DOCTYPE html> <html> <body> <p>Modify object values:</p> <p id="demo"></p> <script> let x = ""; let myObj = { "name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } myObj.cars.car2 = "Mercedes"; for (let i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
33.7使用括号表示法修改值
<!DOCTYPE html> <html> <body> <p>Modify object values using bracket notation:</p> <p id="demo"></p> <script> let x = ""; let myObj = { "name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } myObj.cars["car2"] = "Mercedes"; for (let i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
33.8删除对象属性
<!DOCTYPE html> <html> <body> <h2>Delete JavaScript Object Properties</h2> <p id="demo"></p> <script> let x = ""; let myObj = { "name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } delete myObj.cars.car2; for (let i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
三十四. JSON数组(Arrays)
34.1 访问数组值
<!DOCTYPE html> <html> <body> <h2>Access Array Values</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}'; const myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.cars[0]; </script> </body> </html>
34.2 使用for-in循环遍历数组
<!DOCTYPE html> <html> <body> <h2>Looping an Array</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}'; const myObj = JSON.parse(myJSON); let text = ""; for (let i in myObj.cars) { text += myObj.cars[i] + ", "; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
34.3 使用for循环遍历数组
<!DOCTYPE html> <html> <body> <h2>Looping an Array</h2> <p id="demo"></p> <script> const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}'; const myObj = JSON.parse(myJSON); let text = ""; for (let i = 0; i < myObj.cars.length; i++) { text += myObj.cars[i] + ", "; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
34.4 访问嵌套的JSON数组
<!DOCTYPE html> <html> <body> <p>Looping through arrays inside arrays.</p> <p id="demo"></p> <script> let x = ""; const myObj = { "name":"John", "age":30, "cars": [ {"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]}, {"name":"BMW", "models":["320", "X3", "X5"]}, {"name":"Fiat", "models":["500", "Panda"] } ] } for (let i in myObj.cars) { x += "<h2>" + myObj.cars[i].name + "</h2>"; for (let j in myObj.cars[i].models) { x += myObj.cars[i].models[j] + "<br>"; } } document.getElementById("demo").innerHTML = x; </script> </body> </html>
34.5 修改数组值
<!DOCTYPE html> <html> <body> <p>Modify an array value of an object.</p> <p id="demo"></p> <script> let x = ""; const myObj = { "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] }; myObj.cars[1] = "Mercedes"; for (let i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
34.6 删除数组项
<!DOCTYPE html> <html> <body> <p>Delete array properties:</p> <p id="demo"></p> <script> let x = ""; const myObj = { "name":"John", "age":30, "cars": ["Ford","BMW","Fiat"] } delete myObj.cars[1]; for (let i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body> </html>
三十五. JSON解析(JSON Parse)
35.1 使用JSON解析
<!DOCTYPE html> <html> <body> <h2>Creating an Object from a JSON String</h2> <p id="demo"></p> <script> const txt = '{"name":"John", "age":30, "city":"New York"}' const obj = JSON.parse(txt); document.getElementById("demo").innerHTML = obj.name + ", " + obj.age; </script> </body> </html>
35.2 在AJAX示例中使用JSON解析
<!DOCTYPE html> <html> <body> <h2>Fetch a JSON file with XMLHttpRequest</h2> <p id="demo"></p> <script> const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } xmlhttp.open("GET", "json_demo.txt"); xmlhttp.send(); </script> </body> </html>
35.3 在数组上使用JSON解析
<!DOCTYPE html> <html> <body> <h2>Fetch a JSON file with XMLHttpRequest</h2> <p>Content written as an JSON array will be converted into a JavaScript array.</p> <p id="demo"></p> <script> const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[0]; } xmlhttp.open("GET", "json_demo_array.txt", true); xmlhttp.send(); </script> </body> </html>
35.4 解析日期
<!DOCTYPE html> <html> <body> <h2>Convert a string into a date object.</h2> <p id="demo"></p> <script> const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}'; const obj = JSON.parse(text); obj.birth = new Date(obj.birth); document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; </script> </body> </html>
35.5 使用reviver韩式解析日期
<!DOCTYPE html> <html> <body> <h2>Convert a string into a date object.</h2> <p id="demo"></p> <script> const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}'; const obj = JSON.parse(text, function (key, value) { if (key == "birth") { return new Date(value); } else { return value; } }); document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; </script> </body> </html>
35.6 解析函数
<!DOCTYPE html> <html> <body> <h2>Convert a string into a function.</h2> <p id="demo"></p> <script> const text = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}'; const obj = JSON.parse(text); obj.age = eval("(" + obj.age + ")"); document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); </script> </body> </html>
三十六. JSON字符串化(Stringify)
36.1 使用JSON字符串化
<!DOCTYPE html> <html> <body> <h2>Create a JSON string from a JavaScript object.</h2> <p id="demo"></p> <script> const obj = {name: "John", age: 30, city: "New York"}; const myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> </body> </html>
36.2 在数组上使用JSON字符串化
<!DOCTYPE html> <html> <body> <h2>Create a JSON string from a JavaScript array.</h2> <p id="demo"></p> <script> const arr = ["John", "Peter", "Sally", "Jane"]; const myJSON = JSON.stringify(arr); document.getElementById("demo").innerHTML = myJSON; </script> </body> </html>
36.3 字符串化日期
<!DOCTYPE html> <html> <body> <h2>JSON.stringify() converts date objects into strings.</h2> <p id="demo"></p> <script> const obj = {name: "John", today: new Date(), city: "New York"}; const myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> </body> </html>
36.4 字符串化函数
<!DOCTYPE html> <html> <body> <h2>JSON.stringify() will remove any functions from an object.</h2> <p id="demo"></p> <script> const obj = {name: "John", age: function () {return 30;}, city: "New York"}; const myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> </body> </html>
36.5 使用toString()方法对函数进行字符串化
<!DOCTYPE html> <html> <body> <h2>JSON.stringify() will remove any functions from an object.</h2> <p>Convert functions into strings to keep them in the JSON object.</p> <p id="demo"></p> <script> const obj = {name: "John", age: function () {return 30;}, city: "New York"}; obj.age = obj.age.toString(); const myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> </body> </html>
三十七. JSON PHP
37.1 从php文件中获取JSON
<!DOCTYPE html> <html> <body> <h2>Get JSON Data from a PHP Server</h2> <p id="demo"></p> <script> const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } xmlhttp.open("GET", "demo_file.php"); xmlhttp.send(); </script> </body> </html>
37.2 从php获取JSON数组
<!DOCTYPE html> <html> <body> <h2>Get JSON Data from a PHP Server</h2> <p>Convert the data into a JavaScript array:</p> <p id="demo"></p> <script> const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; } xmlhttp.open("GET", "demo_file_array.php"); xmlhttp.send(); </script> </body> </html>
37.3 从数据库中获取JSON
<!DOCTYPE html> <html> <body> <h2>Get JSON Data from a PHP Server</h2> <p>The JSON received from the PHP file:</p> <p id="demo"></p> <script> const dbParam = JSON.stringify({"limit":10}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; } xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam); xmlhttp.send(); </script> </body> </html>
37.4 循环访问数据库中的结果
<!DOCTYPE html> <html> <body> <h2>Get JSON Data from a PHP Server</h2> <p id="demo"></p> <script> const obj = { "limit":10 }; const dbParam = JSON.stringify(obj); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { myObj = JSON.parse(this.responseText); let text = "" for (let x in myObj) { text += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = text; }; xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam); xmlhttp.send(); </script> <p>Try changing the "limit" property from 10 to 5.</p> </body> </html>
37.5 使用POST方法发送JSON
<!DOCTYPE html> <html> <body> <h2>Use HTTP POST to Get JSON Data from a PHP Server</h2> <p id="demo"></p> <script> const dbParam = JSON.stringify({"limit":10}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { myObj = JSON.parse(this.responseText); let text = ""; for (let x in myObj) { text += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_db_post.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script> <p>Try changing the "limit" property from 10 to 5.</p> </body> </html>
三十八. JSON HTML
38.1 根据JSON数据制作HTML表格
<!DOCTYPE html> <html> <body> <h2>Make a table based on JSON data.</h2> <p id="demo"></p> <script> const dbParam = JSON.stringify({table:"customers",limit:20}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text = "<table border='1'>" for (let x in myObj) { text += "<tr><td>" + myObj[x].name + "</td></tr>"; } text += "</table>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script> </body> </html>
38.2 制作动态HTML表格
<!DOCTYPE html> <html> <body> <h2>Make a table based on the value of a drop down menu.</h2> <select id="myselect" onchange="change_myselect(this.value)"> <option value="">Choose an option:</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <p id="demo"></p> <script> function change_myselect(sel) { const dbParam = JSON.stringify({table:sel,limit:20}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { myObj = JSON.parse(this.responseText); text = "<table border='1'>" for (x in myObj) { text += "<tr><td>" + myObj[x].name + "</td></tr>"; } text += "</table>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); } </script> </body> </html>
38.3 根据JSON数据制作HTML下拉列表
<!DOCTYPE html> <html> <body> <h2>Make a drop down list based on JSON data.</h2> <p id="demo"></p> <script> const dbParam = JSON.stringify({table:"customers",limit:20}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text = "<select>" for (let x in myObj) { text += "<option>" + myObj[x].name + "</option>"; } text += "</select>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script> </body> </html>
三十九. JSON JSONP
39.1 简单的JSOP示例
<!DOCTYPE html> <html> <body> <h2>Request JSON using the script tag</h2> <p>The PHP file returns a call to a function that will handle the JSON data.</p> <p id="demo"></p> <script> function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> <script src="demo_jsonp.php"></script> </body> </html>
39.2 创建动态脚本标签
<!DOCTYPE html> <html> <body> <h2>Click the Button.</h2> <p>A script tag with a src attribute is created and placed in the document.</p> <p>The PHP file returns a call to a function with the JSON object as a parameter.</p> <button onclick="clickButton()">Click me!</button> <p id="demo"></p> <script> function clickButton() { let s = document.createElement("script"); s.src = "demo_jsonp.php"; document.body.appendChild(s); } function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> </body> </html>
39.3 具有动态结果的JSONP示例
<!DOCTYPE html> <html> <body> <p>A script tag with a src attribute is created and placed in the document.</p> <p>The PHP file returns a call to a function with an object as a parameter.</p> <p id="demo"></p> <p>Try changing the table property from "customers" to "products".</p> <script> const obj = { table: "customers", limit: 10 }; let s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s); function myFunc(myObj) { let txt = ""; for (let x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html>
39.4 带有回调函数的JSONP示例
<!DOCTYPE html> <html> <body> <h2>Request With a Callback Function</h2> <p>The PHP file returns a call to the function you send as a callback.</p> <p id="demo"></p> <script> let s = document.createElement("script"); s.src = "demo_jsonp2.php?callback=myDisplayFunction"; document.body.appendChild(s); function myDisplayFunction(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> </body> </html>