JavaScrpt_12 Web API
- 1. JS Composition
- Two, window object
- 3. Timer
- Fourth, the location object
- Five, navigator object
- Six, history object
- 7. Local storage (emphasis)
-
- 1. localStorage (emphasis)
- 2. sessionStorage (understand)
- Comprehensive case
-
- 1. Array map method
- 2. Array join method
1. JS composition
-
ECMAScript:
- It stipulates the core knowledge of js basic grammar.
- For example: variables, branch statements, loop statements, objects, etc.
-
Web APIs:
- DOM Document Object Model, which defines a set of APIs for manipulating HTML documents
- The BOM browser object model defines a set of APIs for manipulating browser windows
2. window object
BOM (Browser Object Model) is the browser object model
- The window object is a global object, which can also be said to be the top-level object in JavaScript
- Like document, alert(), console.log(), these are all properties of window, and the properties and methods of basic BOM are all properties of window
- All variables and functions defined in the global scope through var will become properties and methods of the window object
- Window can be omitted when calling properties and methods under the window object
3. Timer
A function built into JavaScript to delay the execution of code is called setTimeout
Syntax:
setTimeout(callback function, delay time)
setTimeout is only executed once, so it can be understood as delaying the execution of a piece of code, and usually omits the window
Interval function setInterval : Execute every once in a while, , usually omit window
Clear delay function:
clearTimeout(timerId)
be careful
- The delay function needs to wait, so the following code is executed first
- The return value is a positive integer, indicating the number of the timer
<body> <script> // timer delay function // 1. Turn on the delay function let timerId = setTimeout(function () {<!-- --> console.log('I only execute it once') }, 3000) // 1.1 The delay function returns a positive integer number, indicating the number of the delay function console.log(timerId) // 1.2 The delay function requires waiting time, so the following code is executed first // 2. Close the delay function clearTimeout(timerId) </script> </body>
4. location object
location (address) It splits and saves the various components of the URL address, it is an object
Property/Method | Description |
---|---|
href | Attribute, get the complete URL address, used for address jump when assigning values |
search | Attribute, get the parameters carried in the address, symbol ? The latter part |
hash | attribute, get the hash value in the address, the symbol # The latter part |
reload() | method is used to refresh the current page, when the parameter true is passed in, it means forced refresh |
<body> <form> <input type="text" name="search"> <button>Search</button> </form> <a href="#/music">Music</a> <a href="#/download">Download</a> <button class="reload">Refresh the page</button> <script> // location object // 1. The href attribute (key point) gets the complete address, and the assignment is to jump to the new address console.log(location.href) // location.href = 'http://www.itcast.cn' // 2. The search attribute gets the address behind the ? console.log(location.search) // ?search=notebook // 3. The hash attribute gets the address after # console. log(location. hash) // 4. reload method to refresh the page const btn = document.querySelector('.reload') btn.addEventListener('click', function () {<!-- --> // location.reload() // page refresh location.reload(true) // force page refresh ctrl + f5 }) </script> </body>
5. navigator object
Navigator is an object, which records the relevant information of the browser itself
Common attributes and methods:
- Detect browser version and platform through userAgent
// Detect userAgent (browser information) (function () {<!-- --> const userAgent = navigator. userAgent // Verify if it is Android or iPhone const android = userAgent.match(/(Android);?[\s\/] + ([\d.] + )?/) const iphone = userAgent.match(/(iPhone\sOS)\s([\d_] + )/) // If it's Android or iPhone, jump to the mobile site if (android || iphone) {<!-- --> location.href = 'http://m.itcast.cn' }})();
6. History object
History (history) is an object, which mainly manages historical records. This object corresponds to the operation of the browser address bar, such as forward, backward, etc.
Usage scenario
The history object is generally less used in actual development, but it will be seen in some OA office systems.
Common methods:
<body> <button class="back">←Back</button> <button class="forward">Forward→</button> <script> //histroy object // 1. Go forward const forward = document.querySelector('.forward') forward.addEventListener('click', function () {<!-- --> // history. forward() history.go(1) }) // 2. Back const back = document.querySelector('.back') back.addEventListener('click', function () {<!-- --> // history.back() history.go(-1) }) </script> </body>
7. Local storage (emphasis)
Local storage: store data locally in the browser
Common usage scenarios:
- Page refresh data is not lost
benefit:
1. Refresh or close the page without losing data, and achieve data persistence
2. Large capacity, sessionStorage and localStorage are about 5M
1. localStorage (key)
Function: The data can be kept in the local browser for a long time, and the data will not be lost when the page is refreshed or closed
Features: Stored in the form of key-value pairs, and stored as strings, window is omitted
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Local storage-localstorage</title> </head> <body> <script> // local storage - localstorage stores strings // 1. store localStorage. setItem('age', 18) // 2. Get console.log(typeof localStorage.getItem('age')) // 3. delete localStorage. removeItem('age') </script> </body> </html>
2. sessionStorage (understand)
characteristic:
- The usage is basically the same as localStorage
- The difference is: when the page browser is closed, the data stored in sessionStorage will be cleared
Storage: sessionStorage.setItem(key,value)
Get: sessionStorage.getItem(key)
Delete: sessionStorage.removeItem(key)
localStorage stores complex data types
Problem: Only strings can be stored locally, and complex data types cannot be stored.
Solution: It is necessary to convert complex data types into JSON strings and store them locally
Syntax: JSON.stringify(complex data type)
JSON string:
- First is 1 string
- Attribute names are enclosed in double quotes, not single quotes
- If the attribute value is a string type, it must also be double quoted
<body> <script> // Store complex data types locally const goods = {<!-- --> name: 'Xiaomi', price: 1999 } // localStorage. setItem('goods', goods) // console.log(localStorage.getItem('goods')) // 1. Convert the object to a JSON string JSON.stringify localStorage.setItem('goods', JSON.stringify(goods)) // console.log(typeof localStorage.getItem('goods')) </script> </body>
Problem: Because the strings retrieved from the local storage are not objects, they cannot be used directly
Solution: Convert the extracted string into an object
Syntax: JSON.parse(JSON string)
<body> <script> // Store complex data types locally const goods = {<!-- --> name: 'Xiaomi', price: 1999 } // localStorage. setItem('goods', goods) // console.log(localStorage.getItem('goods')) // 1. Convert the object to a JSON string JSON.stringify localStorage.setItem('goods', JSON.stringify(goods)) // console.log(typeof localStorage.getItem('goods')) // 2. Convert JSON string to object JSON.parse console.log(JSON.parse(localStorage.getItem('goods'))) </script> </body>
Comprehensive case
1. Array map method
Usage scenario:
map can traverse the array to process data and return a new array
Syntax:
<body> <script> const arr = ['red', 'blue', 'pink'] // 1. The array map method processes the data and returns an array const newArr = arr. map(function (ele, index) {<!-- --> // console.log(ele) // array element // console.log(index) // index number return ele + 'color' }) console. log(newArr) </script> </body>
map Also known as mapping. Mapping is a term that refers to the relationship between two sets of elements that “correspond” to each other.
The key point of map is that there is a return value, and forEach has no return value (undefined)
2. Array join method
Function: The join() method is used to convert all elements in the array into a string
Syntax:
<body> <script> const arr = ['red', 'blue', 'pink'] // 1. The array map method processes the data and returns an array const newArr = arr. map(function (ele, index) {<!-- --> // console.log(ele) // array element // console.log(index) // index number return ele + 'color' }) console. log(newArr) // 2. The array join method converts the array to a string // If the parentheses are empty, commas will separate console.log(newArr.join()) // red color, blue color, pink color // Parentheses are empty strings, there is no separator between elements console.log(newArr.join('')) //red color blue color pink color console.log(newArr.join('|')) //red color|blue color|pink color </script> </body>