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]
字符串转数组
[...'hello'] // [ "h", "e", "l", "l", "o" ]
箭头函数(=>)
var f = v => v; //等价于 var f = function(v) { return v; };
对象的拷贝Object.assign()
//同名属性,后面覆盖前面 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} //该方法实行的是浅拷贝,即如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用
六、Set、Map
Set
//不能添加相同的值 var s = new Set(); [2, 3, 5, 4, 5, 2, 2].map(x => s.add(x)); [...set] // [1, 2, 3, 4]
Set实例的属性和方法
实例的属性
Set.prototype.constructor
:构造函数,默认就是Set
函数Set.prototype.size
:返回Set
实例的成员总数
实例的方法:
操作方法
add(value)
:添加某个值,返回Set结构本身。delete(value)
:删除某个值,返回一个布尔值,表示删除是否成功。has(value)
:返回一个布尔值,表示该值是否为Set的成员。clear()
:清除所有成员,没有返回值
遍历方法
keys()
:返回一个键名的遍历器values()
:返回一个键值的遍历器entries()
:返回一个键值对的遍历器forEach()
:使用回调函数遍历每个成员
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
Map实例的属性和方法
实例的属性 size属性返回Map结构的成员总数 实例的方法 操作方式 set(key, value):设置key所对应的键值,然后返回整个Map结构(本身) get(key):读取key对应的键值 has(key):返回一个布尔值,表示某个键是否在Map数据结构中 delete(key):删除某个键,返回布尔值 clear():清除所有成员,没有返回值 遍历方法 keys():返回键名的遍历器 values():返回键值的遍历器 entries():返回所有成员的遍历器 forEach():遍历Map的所有成员
七、Generator函数与Promise对象
执行Generator函数会返回一个遍历器对象,也就是说,Generator函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历Generator函数内部的每一个状态。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 }
如果把yield和return一起使用的话, 那么return的值会作为最后的返回值
Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果
// (jquery)封装Promise对象和ajax过程 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) } }); }); }; // 调用示例 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 will the state of p become 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