Common methods for @[TOC] ES5 and ES6
ES5 and ES6
- What we call ES5 and ES6 is actually just a version of the js grammar
- For example, we use WeChat
- The earliest version was unpaid
- Over time, a version emerged that included payment functionality
- ECMAScript is the syntax of js
- Previous versions did not have some functionality
- Some features were added in ES5
- Some features were added at the time of ES6
- Because browsers are manufactured by browser manufacturers
- After ECMAScript has released new features, browser manufacturers need to support these features in their browsers
- This process takes time
- So now, almost all browsers can be fully supported
- Some browsers just don't support them all
- This raises compatibility issues
- So when we write code, we need to consider which methods are ES5 or ES6 to see if browsers support it
1. Common Array Methods for ES5 Increase
1.1 forEach
-
forEach is used to traverse arrays, just like for loop traverses arrays
-
Syntax: Array. forEach(function (item, index, arr) {})
var arr = ['a', 'b', 'c'] // forEach loops through the array, and as many items as there are in the array, the function executes as many times as it does arr.forEach(function (item, index, arr) { // Inside this function // An item is each item in an array // Index is the index for each item // arr is the original array console.log(item) console.log(index) console.log(arr) })
- The code above is equivalent to
var arr = ['a', 'b', 'c'] for (var i = 0; i < arr.length; i++) { fn(arr[i], i, arr) } function fn(item, index, arr) { console.log(item) console.log(index) console.log(arr) }
1.2 map
-
map is used to traverse the array, which is basically the same as forEach, except that it has a return value
-
Syntax: Array. map(function (item, index, arr) {})
-
Return value: a new array
var arr = ['a', 'b', 'c'] // forEach loops through the array, and as many items as there are in the array, the function executes as many times as it does var newArr = arr.map(function (item, index, arr) { // The three parameters inside the function are the same as forEach // Here we can manipulate each item in the array. // Each item after the return operation return item + '11' }) console.log(newArr) // ["a11", "b11", "c11"]
- Return values are our operations on arrays each time
- Equivalent to
var arr = ['a', 'b', 'c'] var newArr = [] for (var i = 0; i < arr.length; i++) { newArr.push(fn(arr[i], i, arr)) } function fn(item, index, arr) { return item + '11' } console.log(newArr)
1.3 filter
-
Filter: iterate through the array to filter out the contents that match our requirements
-
Syntax: Array. Filter (item, index, arr) {})
-
Return value: a new array filtered according to our criteria
var arr = [1, 2, 3, 4, 5] var newArr = arr.filter(function (item, index, arr) { // The three parameters inside the function are the same as forEach // Let's return our terms return item > 2 }) console.log(newArr) // [3, 4, 5]
- All numbers in the new array are greater than 2
- Equivalent to
var arr = [1, 2, 3, 4, 5] var newArr = [] for (var i = 0; i < arr.length; i++) { if (fn(arr[i], i, arr)) { newArr.push(arr[i]) } } function fn(item, index, arr) { return item > 2 } console.log(newArr)
2. JSON
-
json is a special kind of string is, essentially, a string
var jsonObj = '{ "name": "Jack", "age": 18, "gender": "male" }' var jsonArr = '[{ "name": "Jack", "age": 18, "gender": "male" }, { "name": "Jack", "age": 18, "gender": "male" }, { "name": "Jack", "age": 18, "gender": "male" }]'
-
Is a string in which the key and value inside the object are enclosed in double quotes (must be double quotes)
Two Methods of 2.1 JSON
- There are two ways we can use it
- JSON.parse is an object or array that converts a string in json format to a js
- JSON.stringify is a string that converts an object or array of js into a json format
2.1.1 JSON.parse
JSON.parse is an object or array that converts a string in json format to a js
var jsonObj = '{ "name": "Jack", "age": 18, "gender": "male" }' var jsonArr = '[{ "name": "Jack", "age": 18, "gender": "male" }, { "name": "Jack", "age": 18, "gender": "male" }, { "name": "Jack", "age": 18, "gender": "male" }]' var obj = JSON.parse(jsonStr) var arr = JSON.parse(jsonArr) console.log(obj) console.log(arr)
-
obj is the object of our js
-
arr is the array of our js
2.1.2 JSON.stringify
JSON.parse is an object or array that converts a string in json format to a js
var obj = { name: 'Jack', age: 18, gender: 'male' } var arr = [ { name: 'Jack', age: 18, gender: 'male' }, { name: 'Jack', age: 18, gender: 'male' }, { name: 'Jack', age: 18, gender: 'male' } ] var jsonObj = JSON.stringify(obj) var jsonArr = JSON.stringify(arr) console.log(jsonObj) console.log(jsonArr)
- jsonObj is the object string in json format
- jsonArr is an array string in json format
3. this keyword
-
There is a keyword inside each function that is this
-
That we can use directly
-
Important: this inside a function has nothing to do with how the function is called or how the function is defined.
-
Who this inside a function points to depends on how the function is called
-
/* It doesn't matter where the function is defined, just the call to the function 1,Function name () calls this -> window 2,Obj.Function name () this -> obj (excluding arrow functions) 3,Event handler this ->Event source (excluding arrow functions) 4,this inside the timer points to window s 5,The this inside the arrow function points to the same this outside (with the last line this points to) It doesn't matter where this points inside the arrow function and how it is called, just where it is defined */
-
Global defined function called directly, this => window
function fn() { console.log(this) } fn() // this point to window - Method calls inside objects,`this => caller` ```javascript var obj = { fn: function () { console.log(this) } } obj.fn() // This point to obj at this point - The timer's processing function,`this => window` ```javascript setTimeout(function () { console.log(this) }, 0) // This time the this inside the timer processing function points to window
-
Event Handler, this =>Event Source
div.onclick = function () { console.log(this) } // When you click div, this points to div
-
Self-calling function, this => window
(function () { console.log(this) })() // this point to window
-
4. call, apply, and bind
- What we've just said is that this points to the basic way a function is called
- There are three other places where we can ignore the this of the function itself and point away
- These three methods are call / apply / bind
- Is the way to force this to change direction
4.1 call
-
The call method is appended to the function call, ignoring the this point of the function itself
-
Syntax: function name. Call (the this point to change, parameter 1 to pass to the function, parameter 2 to pass to the function,...)
var obj = { name: 'Jack' } function fn(a, b) { console.log(this) console.log(a) console.log(b) } fn(1, 2) fn.call(obj, 1, 2)
- When fn(), this inside the function points to window
- Fn. When call (obj, 1, 2), this inside the function points to the object obj
- When using the call method
- The function will be executed immediately
- The first parameter is the this point inside the function you want to change
- The second parameter begins, passing the parameter to the function in turn
4.2 apply
-
The apply method is appended to the function call, ignoring the this point of the function itself
-
Syntax: function name. Apply (the this point to change, [parameter 1 to pass to the function, parameter 2 to pass to the function,...])
var obj = { name: 'Jack' } function fn(a, b) { console.log(this) console.log(a) console.log(b) } fn(1, 2) fn.call(obj, [1, 2])
- When fn(), this inside the function points to window
- Fn. When apply (obj, [1, 2]), this inside the function points to the obj object
- When using the apply method
- The function will be executed immediately
- The first parameter is the this point inside the function you want to change
- The second parameter is an array in which each item is passed to the function in turn
4.3 bind
-
The bind method is appended to the function call, ignoring the this point of the function itself
-
Unlike call / apply, which does not execute the function immediately, it returns a function that has changed the direction of this
-
Syntax: var newFn =function name. Bind (the this point to change); NewFn (pass parameter)
var obj = { name: 'Jack' } function fn(a, b) { console.log(this) console.log(a) console.log(b) } fn(1, 2) var newFn = fn.bind(obj) newFn(1, 2)
- When called by bind, the function fn is not executed, but a new function is returned.
- This new function is a fn function that changes this to point to the future
- this points to window when fn(1, 2)
- newFn(1, 2) executes the same function as fn, except that this inside points to obj instead
5. ES6 additions
5.1 let and const keywords
-
We used to use the var keyword to declare variables
-
In ES6, two more keywords let and const were used to declare variables
-
It's just a little different from var
-
let and const do not allow duplicate declaration of variables
// It's okay to repeat declaring variables when using var, but you'll just override the front later var num = 100 var num = 200
// Error when using let to repeatedly declare variables let num = 100 let num = 200 // There will be a mistake here
// Error when using const to repeatedly declare variables const num = 100 const num = 200 // There will be a mistake here
-
Variables declared by let and const have no variable promotion (but also have pre-parsing)
// For reasons of pre-parsing (variable promotion), there was this variable before, but it was not assigned console.log(num) // undefined var num = 100
// Because let does not promote variables, it is directly wrong console.log(num) // undefined let num = 100
// Because const does not elevate variables, it is reported as a direct error console.log(num) // undefined const num = 100
-
Variables declared by let and const are restricted by all code blocks
// Variables declared by var can only be restricted by functions, not others if (true) { var num = 100 } console.log(num) // 100
// Variables declared by let, except for functions, can be restricted by all code blocks (if/while/for/...) if (true) { let num = 100 console.log(num) // 100 } console.log(num) // Report errors
// Variables declared by const can be restricted by all code blocks except functions (if/while/for/...) if (true) { const num = 100 console.log(num) // 100 } console.log(num) // Report errors
-
-
The difference between let and const
-
The value of a variable declared by let can be changed, and the value of a variable declared by const cannot be changed.
let num = 100 num = 200 console.log(num) // 200
const num = 100 num = 200 // This is a mistake, because the value of a variable declared by a const cannot be changed (we also call it a constant)
-
let declaration may not be assigned, const declaration must be assigned
let num num = 100 console.log(num) // 100
const num // This is a mistake, because const must be assigned when it is declared
-
5.2 Arrow Function
-
Arrow function is the syntax of an abbreviated function in ES6
-
Important: Arrow functions can only abbreviate function expressions, not declarative functions
function fn() {} // Cannot abbreviate const fun = function () {} // Can be abbreviated const obj = { fn: function () {} // Can be abbreviated }
-
Syntax: (Line parameter of function) => {Code to execute inside the function body}
const fn = function (a, b) { console.log(a) console.log(b) } // You can write using the arrow function const fun = (a, b) => { console.log(a) console.log(b) }
const obj = { fn: function (a, b) { console.log(a) console.log(b) } } // You can write using the arrow function const obj2 = { fn: (a, b) => { console.log(a) console.log(b) } }
SPECIALITY OF 5.2.1 ARROW FUNCTION
-
There is no this inside the arrow function, this is the context of the arrow function
// This line prints this up the number of positions defined by the arrow function // Because this is window here // So this inside the arrow function is window const obj = { fn: function () { console.log(this) }, // this position is the previous line of the arrow function, but it cannot be printed out fun: () => { // The this inside the arrow function is the position where the this can be printed one line after the last line in which the arrow function is written console.log(this) } } obj.fn() obj.fun()
- Judging from our previous this point, both should point to obj
- But because funs are arrow functions, this does not point to obj, but to the outside of funs, which is window
-
There is no arguments parameter set inside the arrow function
const obj = { fn: function () { console.log(arguments) }, fun: () => { console.log(arguments) } } obj.fn(1, 2, 3) // Will print a pseudo array [1, 2, 3] obj.fun(1, 2, 3) // Direct error will be reported
-
When there is only one line argument to a function, it can be written without () The rest must be written
const obj = { fn: () => { console.log('No parameters, parentheses must be written') }, fn2: a => { console.log('A line parameter, not parentheses') }, fn3: (a, b) => { console.log('Two or more parameters, parentheses must be written') } }
-
When the body of a function has only one line of code, it does not write {} and it automatically return s
const obj = { fn: a => { return a + 10 }, fun: a => a + 10 } console.log(fn(10)) // 20 console.log(fun(10)) // 20
Default values for 5.3 function parameters
-
Sometimes we need a default value to appear when defining a function
-
That is, when I do not pass a parameter, I use the default value, pass the parameter and use the passed parameter
function fn(a) { a = a || 10 console.log(a) } fn() // When no arguments are passed, a inside the function is 10 fn(20) // When parameter 20 is passed, a inside the function is 20
- In ES6 we can write the default value directly at the line parameter position of the function
function fn(a = 10) { console.log(a) } fn() // When no arguments are passed, a inside the function is 10 fn(20) // When parameter 20 is passed, a inside the function is 20
- This default value is also used by the Arrow function
const fn = (a = 10) => { console.log(a) } fn() // When no arguments are passed, a inside the function is 10 fn(20) // When parameter 20 is passed, a inside the function is 20
- Note: Arrow function If you need to use the default value, you need to write () for a parameter as well.
5.4 Deconstruction assignment
Deconstructive assignment is a grammatical way to quickly remove members from an object or array
5.4.1 Deconstructing Objects
Quickly get members from objects
// The ES5 method wants members in the object const obj = { name: 'Jack', age: 18, gender: 'male' } let name = obj.name let age = obj.age let gender = obj.gender // Deconstruct assignments to get members from objects const obj = { name: 'Jack', age: 18, gender: 'male' } // The previous {} indicates that I want to get members from obj // name age gender must be a member of obj // obj must be an object let { name, age, gender } = obj
5.4.2 Deconstruction Array
Quickly get members from an array
// ES5 way to get members from an array const arr = ['Jack', 'Rose', 'Tom'] let a = arr[0] let b = arr[1] let c = arr[2] // Getting members from an array by deconstructing assignments const arr = ['Jack', 'Rose', 'Tom'] // The preceding [] indicates that the member is to be retrieved from the arr array // a b c corresponds to index 0 1 2 in this array // arr must be an array let [a, b, c] = arr
5.5.3 Attention
- {} is used specifically to deconstruct objects
- [] is used specifically to deconstruct arrays
- Can't mix
Six. Template String
-
Use''or'' when we represent strings in ES5
-
In ES6, we have one more thing to represent strings, which is `` (inverted quotes)
let str = `hello world` console.log(typeof str) // string
-
Difference between single quote friend double quote
-
Reverse quotation marks can be written on new lines
// This single or double quotation mark cannot be wrapped, and the wrapping will be wrong let str = 'hello world' // This one is wrong below let str2 = 'hello world'
let str = ` hello world ` console.log(str) // Is Available
-
Reverse quotation marks can stitch variables directly inside strings
// When ES5 requires string splicing variables let num = 100 let str = 'hello' + num + 'world' + num console.log(str) // hello100world100 // Writing directly inside a string is not good let str2 = 'hellonumworldnum' console.log(str2) // hellonumworldnum
// Template string stitching variable let num = 100 let str = `hello${num}world${num}` console.log(str) // hello100world100
- The ${} inside ``` is where the variable is written
-
7. Expansion Operator
-
ES6 has a new operator added to it... Called expansion operator
-
The purpose is to expand the array
let arr = [1, 2, 3, 4, 5] console.log(...arr) // 1 2 3 4 5
-
Can be used when merging arrays
let arr = [1, 2, 3, 4] let arr2 = [...arr, 5] console.log(arr2)
-
You can also combine objects to use
let obj = { name: 'Jack', age: 18 } let obj2 = { ...obj, gender: 'male' } console.log(obj2)
-
You can also use this when a function passes parameters
let arr = [1, 2, 3] function fn(a, b, c) { console.log(a) console.log(b) console.log(c) } fn(...arr) // Equivalent to fn(1, 2, 3)
8. Judging data types
8.1 typeof
Judging basic data types
8.2 Object.prototype.toString.call()
Accurate monitoring of data types
9. Function Self-Call
Function is called automatically when defined
<script> // Method 1 (function fn(){ console.log("I am fn function") })() // Method 2 ~function(){ console.log("I am fn function") }() // Method Three !function(){ console.log("I am fun function"); }() // Get the current time from Greenwich Time in milliseconds directly let time = new Date() let ss = time.getTime() console.log(ss) console.log(+new Date()) </script>