1. Extension of Objects
1.1 Object Property Name Expression
ES6 can use [] to wrap the name of a key in JSON.In this case, the key uses an expression as the property name (which is evaluated as a variable), and the key value must be a string.
var a = 'name' var obj = { [a] : "Xiao Ming", age:12, sex:"male" } console.log(obj.name)
1.2 Object.assign() method
This method is used for merging objects, copying all enumerable properties of the source object to the target object.
The first parameter of the Object.assign() method is the target object, followed by the source object.
let obj1 = {a:1}; let obj2 = {a:2, b:3}; let obj3 = {b:4, c:5}; Object.assign(obj1,obj2,obj3) console.log(obj1) console.log(obj2) console.log(obj3)
Be careful:
l It does not return a value and directly changes the first parameter object in Object.assign()
l. An infinite number of objects can be listed later. If the target object has the same name property as the source object, or if multiple source objects have the same name property, the latter property overrides the former property
If the parameter is not an object, it is converted to an object and returned.
typeof Object.assign(2) // "object"
Since undefined and null cannot be converted to objects, errors can occur if they are used as parameters.
Object.assign(undefined) // Report errors Object.assign(null) // Report errors
1.3 Object.keys() method
It converts all the key names of an object into an array object and returns:
let o = {a: 1, b: 2, c: 3}; console.log(Object.keys(o)); //[ 'a', 'b', 'c' ]
1.4 Object.values() method
It converts all the key value s of an object into an array object and returns:
let o = {a: 10, b: 20, c: 33}; console.log(Object.values(o)); //[ 10, 20, 33 ]
1.5 Object.entries() method
It converts all key names and value s of an object into an array object and returns:
let o = {a: 10, b: 20, c: 33};
console.log(Object.entries(o));
1.6 Object.is()
ES5 compares whether two values are equal, with only two operators: the equality operator (==) and the strict equality operator (===).They all have drawbacks, the former automatically converts data types, the latter does not equal itself, and + 0 equals -0.JavaScript lacks an operation and should be equal in all environments as long as the two values are the same.
ES6 proposed the Same-value equality algorithm to solve this problem.Object.is is a new way to deploy this algorithm.It is used to compare whether two values are strictly equal, basically consistent with the behavior of the strict comparison operator (==).
console.log(Object.is('a','a')); //true console.log(Object.is({}, {})); //false console.log(Object.is([], [])); //false //There are only two differences: one is:+0Not equal to-0,The second isNaNEquals itself. console.log(+0 === -0); //true console.log(NaN === NaN); //false console.log(Object.is(+0, -0)); //false console.log(Object.is(NaN, NaN)); //true
2. Extension of strings
2.1 Definition String```Inverse Quotes
String was previously defined and the following delimiters must be used
''or''
Their disadvantage is that they are inconvenient when hyphenating:
var name = "Xiao Ming"; var age = 12; var str = "Hello, I am" + name + "I am this year" + age + "year"; console.log(str)
ES6 uses ``` to delimit:
var str = `Hello`; console.log(str) console.log`str` console.log(typeof str)
var name = "Xiao Ming"; var age = 12; var str = `Hello, I am ${name}I am this year ${age}year`; console.log(str)
Note: Only `` can nest variables with ${}
Dynamic evaluation:
var str = `This year is ${2016 + 2}`; console.log(str); //2018
Write simple operations, function calls, variables, Math functions, array expression methods (map, reduce, filter, join), ternary operators
function sum(a,b){ return a + b; } var str1 = `Ha ${Math.random()}Ha`; var str2 = `Ha ${sum(3,4)}Ha`; var str3 = `Ha ${5 > 10 ? true : false}Ha`; console.log(str1) console.log(str2) console.log(str3)
2.2 String Method
Previously, JavaScript had only the indexOf method, which could be used to determine if one string was contained in another.
ES6 offers three new methods:
Include() Returns a Boolean value, checking for the presence of an item in a string or array
startsWith() returns a Boolean value, checking whether the parameter string begins with the original string
endsWith() returns a Boolean value, checking whether the parameter string ends with the original string
var url = "http://www.aiqianduan.com/"; console.log(url.includes("www")); //true console.log(url.startsWith("http")); //true console.log(url.endsWith("com/")); //true
All three methods support the second parameter, which indicates where to start the search:
let s = 'Hello world!'; console.log(s.includes('Hello', 6)) //false console.log(s.startsWith('world', 6)) //true console.log(s.endsWith('Hello', 5)) //true
The code above indicates that endsWith s behaves differently from the other two methods when the second parameter n is used.It works for the first n characters, while the other two methods work from the nth position to the end of the string.
Repat() returns a new string that can repeat the original string n times
console.log('★'.repeat(10))
3. Extension of Arrays
3.1 find and findIndex methods
The find method of an array instance, used to find the first qualified member of an array, does not traverse the entire array.Its parameter is a callback function, which is executed by all array members in turn until the first member with a return value of true is found, and then the member is returned.If there are no qualified members, undefined is returned.
let arr = [2,3,4,5,6,7,8,9,10,11,12]; let item = arr.find(function(item){ return item > 7; }) console.log(item)
The findIndex() method of an array, like find, returns the subscript position of the first qualified member of the array, or -1 if none of the members match.
let arr = [2,3,4,5,6,7,8,9,10,11,12]; let index = arr.findIndex(function(item){ return item > 7; }) console.log(index); //6
3.2 Array.from() method
Use'...'to make a class array object a real array.
What is a class array object?That is, the object's key names are 0, 1, 2, 3, 4... and have a length attribute that can be enumerated.
var obj = { 0 : 100, 1 : 200, 2 : 300, length:3 } var arr= Array.from(obj); console.log(obj) console.log(arr)
The most common class array object is arguments:
function fun(){ console.log([...arguments]); } fun(1,2,3,4)
3.3 Array.of() method
It can change scattered values into arrays
let arr = Array.of(3,4,5,6,7,8);
console.log(arr)
3.4 include() method
Verify that an item exists in the array:
let arr = [3,4,5,88,100]; console.log(arr.includes(88)); //true console.log(arr.includes(888)); //false
The second parameter of this method represents the starting location of the search, which defaults to 0.If the second parameter is negative, it represents the position of the inverse, if it is greater than the length of the array
(For example, the second parameter is -4, but the array length is 3), it is reset to start at 0.
[1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true
Before this method, we usually use the indexOf method of the array to check if a value is included.
The indexOf method has two drawbacks. First, it is not semantical enough. Its meaning is to find the first occurrence of the parameter value, so it is not intuitive to compare whether it is not equal to -1.Second, it uses the strict equality operator (===) internally to make judgments, which can lead to misjudgement of NaN.
[NaN].indexOf(NaN) // -1
Incudes uses different judgment algorithms, so there is no problem.
[NaN].includes(NaN) // true
3.5 fill() array fill
var arr = new Array(10).fill("★"); console.log(arr)
3.6 for of traversal
An array traversal method, called for of traversal, has been added, usually with arr.entries()
var arr = ['Whiteboard','Chicken','Two Articles','Triple cakes','Four barrels']; for(var v of arr){ console.log(v) }
var arr = ['Whiteboard','Chicken','Two Articles','Triple cakes','Four barrels']; for(var [k,v] of arr.entries()){ console.log(k,v) }
4. New features of functions in ES6
4.1 Arrow Function (Focus)
ES6 allows functions to be defined using arrows (=>):
Be careful:
l = > is a complete operator and cannot be split = >
l Arrow function must be anonymous. To name this anonymous arrow function, use the'='assignment to receive an anonymous arrow function.
Extensions to functions: http://es6.ruanyifeng.com/#docs/function
l [Basic simplification of function]
const sum = function(a, b){ return a + b; }
Equivalent to, now with the definition of the arrow function:
const sum = (a, b)=>{ return a + b; }
[Both return and {}, () can be simplified]
const sum = (a,b)=> a + b;
console.log(sum(4,5))
Simplify'{}'and return if there is only one return statement in the arrow function
Implicit: If there is more than one statement, you must add'{}'and return statements
If there is only one parameter in the Arrow Function parameter variable, the parenthesis'()'of the parameter variable may not be written
const mianji = r => 3.14 * r * r
console.log(mianji(10))
If the arrow function does not require parameters, use a parenthesis to represent the parameter part.
const f = ()=> 5 // Equivalent to const f = function(){ return 5; }
Since'{}'is resolved to a function body, if the arrow function returns an object directly, parentheses must be placed around the object or an error will be reported.
// const fun = (id,name)=> {"id": id, "name": name} //Report errors const fun = (id,name)=> ({"id": id, "name": name}) console.log(fun(10001,"Xiao Ming"))
Arrow functions can be written continuously to denote the nesting of functions, and the outer function returns a function.
const fun = a=> b=> a + b;
console.log(fun(10)(5))
Equivalent to the following two writings:
const fun = (a)=>{ return (b)=>{ return a + b; } }
function fun(a){ return function(b){ return a + b; } }
Note: The arrow function has several usage considerations.
(1) The this object in the function body is the object in which it is defined, not the object in which it is used.
(2) It cannot be used as a constructor, that is, you cannot use the new command, otherwise an error will be thrown.
(3) You cannot use the arguments object, which does not exist in the function body.If you want to use it, you can use the rest parameter instead.
(4) The yield command cannot be used, so the arrow function cannot be used as a Generator function.
Of the four points above, the first one is of particular note.The direction of this object is variable, but it is fixed in the arrow function.
Remaining parameters of 4.2 function
ES6 introduces the rest parameter (in the form of a variable name) to get extra parameters for the function so that the arguments object is not needed.The rest parameter is matched with a variable that puts extra parameters into the array.
Like normal functions, arrow functions can also use the default and remaining parameters of ES6:
const fun = (a,...b)=>{
console.log(a)
console.log(b)
}
fun(1,2,3,4,5,6);
Default parameters for 4.3 functions
ES6 allows you to set default values for the parameters of a function, which are written directly after the parameter definitions:
const sum = (a, b=10)=>{ return a + b; } console.log(sum(3,4)); //7 console.log(sum(3)); //13
A default value of 10 is assigned to the parameter of the function, indicating that the default value will not take effect until a value of b is passed in when called.
4.4 Arrow Function Context
Previous Judgment Context
Rule 1: fn() is called directly in parentheses, where this is window Rule 2: Object peer calls obj.fn(), where this is obj Rule 3: The enumeration function in the array calls arr[3](), where this is arr Rule 4: The timer calls the function setInterval (fn, 10), where this is window Rule 5: Button's event listens on oBtn.onclick = fn, where this is oBtn Rule 6: call and allpay can be specified, fn.call(obj), where this is obj Rule 7: Call the function with new, new fn(), where this is a newly created, secret blank object. The above rules do not apply to arrow functions!
What is the context rule for the arrow function?
The context of an arrow function is the context in which the function is defined, not how it is called.
Who is this within the function where the arrow function is defined and who is this arrow function for life cannot be changed.
Title 1: Scenarios. Timers used to be backed up frequently. Now with arrow functions, backups are not needed:
var obj = { a : 10, fn: function(){ setInterval(()=>{ console.log(this.a) },1000) } } obj.fn()
The context of the red function is obj, where the context of the arrow function inherits from the obj object instead of window.
l Title 2: The fun function has an arrow function inside and the arrow function executes
function fun(){ const fn = ()=>{ console.log(this.a) } fn(); } var laowang = { a : 666, fun : fun } laowang.fun();
Since the funfunfunction is called by laowang, the context of the funfunction is laowang, and the context of the arrow function is laowang.
Because the context of the arrow function is the context of the function in which the arrow function is defined.
l equals backing up this externally once:
function fun(){ var self = this; const fn = function(){ console.log(self.a) } fn(); } var laowang = { a : 666, fun : fun } laowang.fun();
l Title 3:
var obj = { say : function(){ var f1 = ()=>{ console.log(this); //obj setTimeout(()=>{ console.log(this); //obj }) } f1(); } } obj.say();
Because the F1 definition is that this in the function in which it is located points to obj, the arrow function this of setTimeout inherits from f1, so no matter how many levels of nesting there are, it is obj.
Extensions to Topic 3:
var obj = { say : function(){ var f1 = function(){ console.log(this); //window setTimeout(()=>{ console.log(this); //window }) } f1(); } } obj.say();
Result: window, because the arrow function is defined in the same environment as window, this inside the arrow function is window (the node environment has no window and can be executed in the browser)
That is, the context of the arrow function depends on how it is defined, not how it is called, as opposed to the usual function.
Further, the context of the arrow function cannot be changed.
Title 4:
function fun(){ const fn = ()=>{ console.log(this.a) } const xiaohua = { a : 9999999 } fn.call(xiaohua); //Neither call nor apply can change the context of the arrow function } var laowang = { a : 666, fun : fun } laowang.fun();
The output is laowang's a, or 666, and the arrow function context cannot be changed for life.
Arrow functions cannot be call ed, applied
function has not been laid off yet
If a variable context function is required, use function
If you need a function that automatically backs up external context, use the arrow function
4.5 bind() binding context
Only functions can be bind(), arrow functions cannot be bind()
If a function is pointed to an object by bind(), then the function context will be bound to the object for life, never changing, neither call nor apply changing.
Note: bind() binds context only, but does not execute functions, unlike call and apply.
function fun(){ console.log(this.a); } var laowang = { a : 666 } var xiaozhang = { a : 8888 } fun = fun.bind(laowang); //fun The context of a function lifelong is laowang fun(); //Even if called in parentheses fun Function, also laowang fun.call(xiaozhang); //call and apply Nor can it change, or laowang fun.apply(xiaozhang); fun = fun.bind(xiaozhang); //again bind Is it invalid, or laowang setInterval(fun,1000); //Timer can't change it either
As long as you write bind() once, there is no way to change the this direction of the function.
4.6 Double Colon Operator
Arrow functions bind this objects, greatly reducing the explicit binding of this object's writing (call, apply, bind).However, the arrow function does not work in all situations, so now there is one proposal A function bind operator is proposed to replace call, apply, and bind calls.
Function binding operators are two colons side by side (:), a double colon is an object on the left and a function on the right.This operator automatically binds the left object as the context (that is, the this object) to the right function.(
foo::bar; // Equivalent to bar.bind(foo); foo::bar(...arguments); // Equivalent to bar.apply(foo, arguments);
4.7 Simplification of functions in objects
var result = Object.keys(obj).map(item=>({ "label": item, "children" : obj[zimu].map(pinpai=>({ "label" : pinpai.brand , "children": pinpai.series.map(chexi=>({ "label" : chexi })) })) }));
var obj = { a : 100, fun : function(){ console.log(this.a); } }
Equivalent to:
var obj = { a : 100, fun(){ console.log(this.a); } } obj.fun();
Not equal to:
var obj = { a : 100, fun:()=>{ console.log(this.a); } } obj.fun();
4.8 babel translates them
Pre-translation |
Post-translation |
|
|
The arrow function is to automatically back up this.
Exercise: There is an object below that will not change the original object, create a new obj2 object, and change the area with id of 2 car owners to "China".
Practicevar obj1 = { "nowshow": 8, "nowType":"All", "dataArr":[ { "id":1, "brand":"Benz", "price":50, "saler":{ "name":"Wang Nima", "provice":"Germany" } }, { "id":2, "brand":"BMW", "price":20, "saler":{ "name":"Whole Egg Li", "provice":"The Republic of Korea" } } ] };