Reprinted from: http://blog.csdn.net/column/details/es6-study.html
1. let and const commands
Variables declared with let and const are only valid within code blocks
There is no variable promotion
The variable must be used after the declaration, otherwise an error will be reported
Duplicate declarations are not allowed
const command
- Declare a read-only constant, once declared, the value of the constant cannot be changed
- Once a variable is declared, it must be initialized immediately and cannot be left for later assignment
The global variables declared by the let command, const command, and class command are not properties of the global object
let b = 1; window.b // undefined
2. Destructuring assignment
Array destructuring assignment
let [foo, [[bar], baz]] = [1, [[2], 3]]; let [ , , third] = ["foo", "bar", "baz"]; let [head, ...tail] = [1, 2, 3, 4];Assigning undefined to the corresponding position will not affect the default value
var [x = 1] = [undefined]; x // 1
Object destructuring differs from arrays in one important way. The elements of the array are arranged in order, and the value of the variable is determined by its position; while the properties of the object have no order, the variable must have the same name as the property to get the correct value.
String destructuring assignment
const [a, b, c, d, e] = 'hello';
Destructuring assignment of function parameters
function add([x, y])
use:
variable swap
[x, y] = [y, x];
function returns multiple values
return [1, 2, 3];
function definition
function f([x, y, z]) { ... }
Extract JSON data
let { id, status, data: number } = jsonData;
Default values for function parameters
function foo(x = 11, y = 31)
3. String expansion
for...of loop through the string
for (let i of text){ ... }Is a string contained within another string, ES5 only has indexof
- includes(): Returns a boolean value indicating whether the parameter string was found
- startsWith(): Returns a boolean value indicating whether the parameter string is at the head of the source string
- endsWith(): Returns a boolean value indicating whether the parameter string is at the end of the source string
Repeat the original string n times
'x'.repeat(3) // "xxx"padStart() and padEnd() complete the length. The first value is the minimum length. If the second value is omitted, the default is to use a space to complete it. If it is equal to or greater than the minimum length, the original string is returned. After the completion exceeds the minimum length, the complement Intercept the entire string
'x'.padStart (5,' ab ') //' ababx ' 'x'.padEnd (4,' ab ') //' xaba ' 'xxx'.padStart(2, 'ab') // 'xxx' 'abc'.padStart(10, '0123456789')// '0123456abc' 'x'.padStart(4) // ' x'
template string
// multiline string `In JavaScript this is not legal.`
// embed variable in string var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`
Common String Methods in ES5
toUpperCase()
Convert a string to all uppercasetoLowerCase()
Convert a string to all lowercaseindexOf()
will search for the occurrence of the specified stringsubstring()
Returns a substring of the specified index rangesplit()
split string into string arrayreplace()
Replace substrings that match a regular expressionsearch()
Retrieve values that match a regular expression
4. Values and Arrays
Numerical expansion
Number.isFinite(), Number.isNaN()
Number.parseInt(), Number.parseFloat()
array expansion
Array.from()
Array.from
The method is used to convert two types of objects into real arrays: array-like objects and iterable objects (including ES6's new data structures Set and Map)
Array.of()
Array.of
The method is used to convert a set of values into an array. The main purpose is to make up for the deficiencies of the array constructor Array().
Array.of(3, 11, 8) // [3,11,8]
copyWithin()
copyWithin inside the current array , copies the members of the specified position to other positions (will overwrite the original members)
- target (required): start replacing data at this position
- start (optional): start reading data from this position, the default is 0. If negative, it means reciprocal
- end (optional): stop reading data before reaching this position, the default is equal to the length of the array. If negative, it means reciprocal
// copy bit 3 to bit 0 [1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5]
The find method is used to find the first qualified array member, if there is no return undefined
findIndex method, returns the position of the first qualified array member, if there is none, it returns -1
fill array
['a', 'b', 'c'].fill(7) // [7, 7, 7] ['a', 'b', 'c'].fill(7, 1, 2)//fill value, start position, end position // ['a', 7, 'c']
The entries(), keys() and values() of array instances are all traversal methods
for (let index of ['a', 'b'].keys()) {//traverse key names} for (let elem of ['a', 'b'].values()) {//traverse key values} for (let [index, elem] of ['a', 'b'].entries()) {//traverse key-value pairs}
empty space in array
0 in [undefined, undefined, undefined] // true 0 has a value 0 in [, , ,] // false 0 position has no value
Common Array Methods in ES5
concat()
Concatenate two or more arrays and return the resultjoin()
Put all elements of the array into a string. Elements are separated by the specified delimiterpop()
Remove and return the last element of an arraypush()
Add one or more elements to the end of the array and return the new lengthreverse()
Reverse the order of elements in an arrayshift()
Remove and return the first element of an arrayslice(start,end)
Returns the selected element from an existing array
- start: Required, specifies where to start the selection. If negative, it specifies the position from the end of the array
- end: optional, specifies where to end the selection. This parameter is the array subscript at the end of the array fragment. If this parameter is not specified, the sliced array contains all elements from start to end of the array. If this parameter is negative, it specifies the element counted from the end of the array
sort(sortby)
Sort the elements of an array, sortby is optional, but must be a functionsplice(index,howmany,item1,.....,itemX)
Remove elements and add new elements to the array
- index: Required. Integer specifying the position to add/remove items, use a negative number to specify the position from the end of the array
- howmany: Required. The number of items to delete. If set to 0, the item will not be deleted
- item1,…..,itemX: Optional. new item added to the array
unshift()
Add one or more elements to the beginning of an array and return the new length
5. Functions and Objects
function log(x, y = 'World') {}//The default value of the parameter log('Hello', 'China') // Hello China
function foo({x, y = 5}) {}//Use in conjunction with destructuring assignment defaults foo({x: 1, y: 2}) // 1, 2
application
Merge arrays
[...arr1, ...arr2, ...arr3]
const [first, ...rest] = [1, 2, 3, 4, 5]; first // 1 rest // [2, 3, 4, 5]
String to array
[...'hello'] // [ "h", "e", "l", "l", "o" ]
Arrow function (=>)
var f = v => v; //Equivalent to var f = function(v) { return v; };
A copy of the object Object.assign()
//Properties with the same name, the back covers the front var target = { a: 1, b: 1 }; var source1 = {b: 2, c: 2}; var source2 = {c: 3}; Object.assign(target, source1, source2); target // {a:1, b:2, c:3} //This method implements a shallow copy, that is, if the value of an attribute of the source object is an object, then the copy of the target object is a reference to this object
Six, Set, Map
Set
// cannot add the same value var s = new Set(); [2, 3, 5, 4, 5, 2, 2].map(x => s.add(x)); [...set] // [1, 2, 3, 4]
Properties and methods of Set instances
instance properties
Set.prototype.constructor
: Constructor, the default is aSet
functionSet.prototype.size
: returnsSet
the total number of members of the instance
Instance methods:
How to operate
add(value)
: Add a value and return the Set structure itself.delete(value)
: Delete a value and return a boolean value indicating whether the deletion was successful.has(value)
: Returns a boolean value indicating whether the value is a member of a Set.clear()
: clear all members, no return value
traversal method
keys()
: Returns a iterator of key namesvalues()
: Iterator that returns a key valueentries()
: Returns a iterator of key-value pairsforEach()
: loop through each member using a callback function
Map
var m = new Map(); var o = {p: "Hello World"}; m.set(o, "content") m.get(o) // "content" m.has(o) // true m.delete(o) // true m.has(o) // false
Properties and methods of Map instances
instance properties The size property returns the total number of members of the Map structure instance method Operation method set(key, value): Set the key value corresponding to the key, and then return the entire Map structure (itself) get(key): read the key value corresponding to the key has(key): Returns a boolean value indicating whether a key is in the Map data structure delete(key): delete a key and return a boolean value clear(): clears all members, no return value traversal method keys(): Returns a traverser of key names values(): iterator that returns key values entries(): Returns a traverser of all members forEach(): iterates over all members of the Map
7. Generator function and Promise object
Executing the Generator function will return a traverser object, that is, the Generator function is a traverser object generation function in addition to the state machine. The returned traverser object can traverse each state inside the Generator function in turn.function* helloWorldGenerator() { yield 'hello'; yield 'world'; return 'ending'; } var hw = helloWorldGenerator (); hw.next() // { value: 'hello', done: false } hw.next() // { value: 'world', done: false } hw.next() // { value: 'ending', done: true } hw.next() // { value: undefined, done: true }
If you use yield and return together, the value of return will be used as the final return value
Promise, simply put, is a container that holds the result of an event (usually an asynchronous operation) that will end in the future
// (jquery) encapsulates the Promise object and the ajax process var jqGetAjaxPromise = function(param){ return new Promise(function(resolve, reject){ $.ajax({ url: param.url, type: 'get', data: param.data || '', success: function(data){ resolve(data); }, error: function(error){ reject(error) } }); }); }; // call example var p2 = jqGetAjaxPromise ({ url: 'cross-domain1.txt' }); p2.then(function(data){ console.log(data); return jqGetAjaxPromise({ url:'cross-domain2.txt' }); }).then(function(data2){ console.log(data2); }).catch(function(err){ console.log(err); });
Promise.all()
var p = Promise.all([p1, p2, p3]); //p1, p2, p3 are all instances of Promise objects, if not, the Promise.resolve method will be called first //Convert the parameter to a Promise instance for further processing
The state of p is determined by p1, p2, and p3, and is divided into two cases:
1. Only when the states of p1, p2, and p3 become fulfilled, the state of p becomes fulfilled. At this time, the return values of p1, p2, and p3 are composed of An array passed to the callback function of p
2. As long as one of p1, p2, and p3 is rejected, the status of p becomes rejected, and the return value of the first rejected instance will be passed to p Callback
Promise.race()
var p = Promise.race([p1, p2, p3]); //p1, p2, p3 are all instances of Promise objects, if not, the Promise.resolve method will be called first //Convert the parameter to a Promise instance for further processing
As long as an instance of p1, p2, and p3 changes the state first, the state of p changes accordingly. The return value of the Promise instance that changed first is passed to the callback function of p
Eight, Class
Constructor: constructor()Inheritance: class ColorPoint extends Point{ ... } subclasses must call the super method in the constructor method