1. Introduction
A few days ago, I rewrote one of my code bases with es6 syntax. It is said to be a rewrite, but in fact, the changes are not much and the work is not much. At the end of the rewrite, I personally summarized some common grammar used in ES6 and its advantages over ES5. The following syntax may account for 10%-20% of es6’s new features, but it accounts for about 80% of the development. The following articles are classified by the new features commonly used in ES6. Some of the examples mentioned in this article are small examples from my code base, while others are made up by myself. Hope to help you, if you think there is something wrong, or where to write wrong, welcome to point out!
For those of you who don’t know what I mean by codebase, simply type an AD: this codebase is 57 small instances of javascript that I encapsulate, such as: array deduplication, character substitution, common Dom operations, lazy image loading, etc. (see the instructions). The code has been uploaded to Github! Es5 version — EC-DO-1.1.4. Es6 version — EC-do-2.0.0. Welcome to Star. Also hope that you can give more advice, or together with everyone to improve this project! 2. As for how to use the code base, go to Github and have a look. 3. It’s been more than two years since ES6 was released, and now es7 and ES8 have been released, but there’s not much new about ES7 and ES8. Check out the following two links! Learn ES7+ES8 in 10 minutes.
2.let const
Let is different from var in that let has the distinction of block-level scope.
The following example
// Declare a global I variable.for(var i=0; i<10; i++){ console.log(i) } console.log('Final value:'+i)
Copy the code
// J is only in this oneforThe loop is valid. If called outside the loop, an error will be reportedfor(letj=0; j<10; j++){ console.log(j) } console.log('Final value:'+j)Copy the code
Another common usage scenario is: if you have five li’s on a page, the index would be 0,1,2,3,4. Click on a li to display its index.
var oLi= document.querySelectorAll('li')
for (var i = 0,len = oLi.length; i < len; i++){
oLi[i].onclick = function(){
console.log(i)
}
}
Copy the code
So if I write it this way, it’s actually going to show me 5 whenever I click on that Li. Because by the time I click on li, the above code has been executed, so each I, which is equal to 5, will show 5.
You don’t have this problem with let
var oLi= document.querySelectorAll('li')
for (let i = 0,len = oLi.length; i < len; i++){
oLi[i].onclick = function(){
console.log(i)
}
}
Copy the code
With let, if you click on the first li, it displays a 0, and if you click on the third li, it displays a 2. You can try this on your own!
So let, let’s say const, const initializes an assignment and then you can’t change the assignment. The diagram below.
I currently use this for reference plug-ins, libraries, or modular development!
Such as the above, in the development can be brought by the name of the exception!
3.arrow function
Arrow function, the frequency of use is very high! Writing method is also very concise and clear!
The following array summation instance
//sumArr is a property of ecDo in this object, but es6 and ES5 are defined differently. //es6 -- implicit return sumArr(arr) {returnArr. Reduce ((pre, cur) =>pre + cur)}return arr.reduce((pre, cur) =>{return} //es5 sumArr:function (arr) {
return arr.reduce(function (pre, cur) {
return pre + cur
})
},
Copy the code
Another common scenario is when a setTimeout or setInterval is used. The following “image lazy loading instance” (code temporarily can not see too fine, look at the picture is good, paste the code is to let everyone see the whole function, do not let everyone deceive). Process unknown detail, see ES6 and ES5 use difference!
//es6 (); // Es6 (); loadImg(className ='ec-load-img', num = 0, errorUrl = null) {
let oImgLoad = document.getElementsByClassName(className);
for (leti = 0, len = oImgLoad.length; i < len; I++) {// if the image has been scrolled to the specified heightif(document.documentElement.clientHeight + document.documentElement.scrollTop > oImgLoad[i].offsetTop - num && ! OImgLoad [I].isload) {// Record whether the image has been loaded oImgLoad[I].isload =true; // Set the transition to have an image transparency change when the image comes down oImgLoad[I].style. CssText ="transition: ''; opacity: 0;";
if (oImgLoad[i].dataset) {
this.aftLoadImg(oImgLoad[i], oImgLoad[i].dataset.src, errorUrl, function(o) {// Add a timer to ensure that the image has been loaded, and then remove the class specified by the image to avoid repeated editingsetTimeout(()=>{
if (o.isLoad) {
this.removeClass(o, className);
o.style.cssText = ""; }}, 1000)}); }else {
this.aftLoadImg(oImgLoad[i], oImgLoad[i].getAttribute("data-src"), errorUrl, function(o) {// Add a timer to ensure that the image has been loaded, and then remove the class specified by the image to avoid repeated editingsetTimeout(()=>{
if (o.isLoad) {
this.removeClass(o, className);
o.style.cssText = ""; }}, 1000)}); } (function (i) {
setTimeout(()=>{
oImgLoad[i].style.cssText = "transition:all 1s; opacity: 1;"; }, 16) })(i); }}} //es5function (className, num, errorUrl) {
var _className = className || 'ec-load-img', _num = num || 0, _this = this,_errorUrl=errorUrl||null;
var oImgLoad = document.getElementsByClassName(_className);
for(var i = 0, len = oImgLoad.length; i < len; I++) {// if the image has been scrolled to the specified heightif(document.documentElement.clientHeight + document.documentElement.scrollTop > oImgLoad[i].offsetTop - _num && ! OImgLoad [I].isload) {// Record whether the image has been loaded oImgLoad[I].isload =true; // Set the transition to have an image transparency change when the image comes down oImgLoad[I].style. CssText ="transition: ''; opacity: 0;"
if (oImgLoad[i].dataset) {
this.aftLoadImg(oImgLoad[i], oImgLoad[i].dataset.src, _errorUrl, function(o) {// Add a timer to ensure that the image has been loaded, and then remove the class specified by the image to avoid repeated editingsetTimeout(function () {
if (o.isLoad) {
_this.removeClass(o, _className);
o.style.cssText = ""; }}, 1000)}); }else {
this.aftLoadImg(oImgLoad[i], oImgLoad[i].getAttribute("data-src"), _errorUrl, function(o) {// Add a timer to ensure that the image has been loaded, and then remove the class specified by the image to avoid repeated editingsetTimeout(function () {
if (o.isLoad) {
_this.removeClass(o, _className);
o.style.cssText = ""; }}, 1000)}); } (function (i) {
setTimeout(function () {
oImgLoad[i].style.cssText = "transition:all 1s; opacity: 1;"; }, 16) })(i); }}}Copy the code
With so much code pasted, there are actually three small differences
A quick explanation: When using an arrow function, the this object in the body of the function is the object that was defined, not the object that was used. The reason for this is that the arrow function does not have this. Its this is inherited from the outside, so the inner this is the outer code block’s this.
4.template string
Template string, this common use of frequency is also very high, but also very practical!
The following example is the countdown to a certain time
//es6 getEndTime(endTime) {letstartDate = new Date(); // Start time, current timeletendDate = new Date(endTime); // End time, pass the time parameterlett = endDate.getTime() - startDate.getTime(); // The number of milliseconds of the time differencelet d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
return'Remaining time${d}day${h}hours${m}minutes${s}seconds"`; } getEndTime: function (endTime) {var startDate = new Date(); Var endDate = new Date(endTime); Var t = enddate.gettime () -startdate.gettime (); Var d = 0, h = 0, m = 0, s = 0; if (t >= 0) { d = Math.floor(t / 1000 / 3600 / 24); h = Math.floor(t / 1000 / 60 / 60 % 24); m = Math.floor(t / 1000 / 60 % 60); s = Math.floor(t / 1000 % 60); } return "For the rest of" + d + "day" + h + "hours" + m + "minutes" + s + " 秒";
}
Copy the code
If you’re not sure how to use a template string, let’s do another example, such as adding a large section of HTML to a div. What ES5 does is
var obj={
author:'wait',
time:'2017.11.8',
thing:'Look at the convenience of template strings. '
}
$("#test").append(
"< p > this is < I >" + obj.author+ "</i> " +
"An instance of writing. This instance is for" +
"<i>" + obj.thing +
"</i>"+"+obj.time+
"</span></p>"
);Copy the code
With ES6, it’s much easier
let obj={
author:'wait',
time:'2017.11.8',
thing:'Look at the convenience of template strings. '
}
$("#test").append(' <p> This is < I >${obj.author}</ I > An instance of write. This example is for < I >${obj.thing}< p style = "max-width: 100%; clear: both;${obj.time}</span>
</p>`
); Copy the code
5.destructuring
Deconstruction assignment this is used more, simple and clear, is a shorthand!
//es5
var name='wait'
var sex='male'
var info= {name:name, sex: sex}
console.log(info) //Object {name: "Waiting", sex: "Male"}
//es6
let name='wait'
let sex='male'
let info= {name, sex}
console.log(info) //Object {name: "Waiting", sex: "Male"} // Es6 can be reversedlet info={name: "Waiting", sex: "Male"};
let {name,sex}=info;
console.log(name,sex)// "Waiting" "Male"
Copy the code
6.default, rest
Default, which is the default value of the function argument, is easy to understand
FormatText (STR, size = 3, delimiter = 3)', ') {
let regText = '\\B(? =(\\w{' + size + '}) + (? ! \\w))';
let reg = new RegExp(regText, 'g');
returnstr.replace(reg, delimiter); } //es5 formatText:function (str, size, delimiter) {
var _size = size || 3, _delimiter = delimiter || ', ';
var regText = '\\B(? =(\\w{' + _size + '}) + (? ! \\w))';
var reg = new RegExp(regText, 'g');
return str.replace(reg, _delimiter);
}Copy the code
Rest, I don’t know how to say this, look at the following example
functionparam(first,... all){ console.log(first) console.log(all) console.log(Object.prototype.toString.call(all)) } animals('The first'.'The second'.'The third')
Copy the code
All is an array. You don’t have to convert arguments to an array!
7.export & import
The corresponding feature of these two is modular development, which is arguably the most useful new feature! Powerful, but easy to write! Just a few codes! Look at picture!
When encapsulating a module, use export to expose the module
When needed, use import to proceed, done
Another on-demand approach, by the way
8. The API is recommended
8-1. The string
repeat
The repeat method returns a new string, indicating that the original string is repeated n times.
'wait'.repeat(3)
//"Waiting, waiting, waiting."Copy the code
includes & startsWith & endsWith
Includes: Whether the parameter string was found. Returns a Boolean value. StartsWith: whether the argument string is at the head of the original string, returns a Boolean value. EndsWith: whether the argument string is at the end of the original string, returns a Boolean value.
Each of the three methods takes two arguments, the first a parameter string and the second a place to start the retrieval
var str='I am waiting'
str.startsWith('I am') / /true
str.startsWith('我') / /true
str.startsWith('我', 2) / /false
str.startsWith('wait') / /false
str.endsWith('wait') / /true
str.includes('wait') / /true
str.includes('我'And 3) / /false
Copy the code
padStart & padEnd
PadStart: If the string is not long enough, complete the character in the header. PadEnd: If the string is not long enough, complete the character in the tail
Both methods take two arguments, the first to specify the minimum length of the string, and the second to complete the string. If the length of the string is specified, it is equal to or greater than the specified minimum length (first argument). If you ignore the second argument, you complete the string with Spaces!
var str='wait'
str.padEnd(10,'123') / /"Waiting for 12312312"
str.padStart(10,'123') / /"12312312 waiting for"
str.padEnd(10)//"Waiting"
str.padStart(10)//"Waiting"
str.padStart(1)//"Waiting"
str.padEnd(1)//"Waiting"Copy the code
8 – (2) values
isNaN
Check whether a value is NaN
Number.isNaN(NaN)//true
Number.isNaN(15)//falseCopy the code
isInteger
To determine whether a value is an integer, note that, for example, 1 and 1.0 are integers.
Number.isInteger(1)//true/ / Number. IsInteger (1.0)true/ / Number. IsInteger (1.1)false
Copy the code
sign
Determine whether a number is positive, negative, or zero
Math.sign(-10)// -1
Math.sign(10)// +1
Math.sign(0)// +0
Math.sign(-0)// -0
Math.sign(NaN)// NaN
Math.sign('10')// +1
Math.sign('wait')// NaN
Math.sign(' ')// 0
Math.sign(true)// +1
Math.sign(false)// 0
Math.sign(null)// 0
Copy the code
trunc
Return the integer part of a number by dividing the fractional part
Math.h trunc (1.1) / / 1 math.h trunc (1.1) / / - 1 math.h trunc (0.1) / / 0 math.h trunc ('123.456')//123
Math.trunc('wait')//NaN
Copy the code
8-3. The object
assign
Used for merging objects, copying to target objects.
var _name={name:'wait'},sex={sex:'male'},city={'city':'guangzhou'}
Object.assign(_name,sex,city)//{name: "Waiting", sex: "Male", city: "Guangzhou"}
var info1={name:'keep',sex:'male'},info2={name:'wait',city:'guangzhou'}
Object.assign(info1,info2)//{name: "Waiting", sex: "Male", city: "Guangzhou"}Copy the code
If info1 or Info3 is modified, info3 or Info1 will not be affected. However, object. assign is not a deep copy. For more details, see my previous post on Object Depth Copying
var info1={name:'keep',sex:'male'}
var info3=Object.assign(info1,{})//{name:'keep',sex:'male'}Copy the code
keys
An array is returned by iterating over the key names of the object itself
var info={name: "Waiting", sex: "Male", city: "Guangzhou"}
Object.keys(info)//["name"."sex"."city"]
Copy the code
values
An array is returned by iterating over the keys of the object itself
Object.values(info)//["Waiting"."Male"."Guangzhou"]
Copy the code
entries
An array is returned by iterating over the key-value pairs that the object itself can traverse
Object.entries(info)//[["name"."Waiting"], ["sex"."Male"], ["city"."Guangzhou"]]
Copy the code
8-4 array
from
From is used to turn two types of objects into true arrays: array-like objects and traversable objects
Array.from('wait') / / /"Keep"."Waiting"] // Convert arguments to a real arraylet oLi = document.querySelectorAll('li');
Array.from(oLi ).forEach(function(item) { console.log(item); }); / / the arguments objectfunction fn() {
letargs = Array.from(arguments); } // By the way, Setlet newSet = new Set(['a'.'b'.'a'.'c'])
Array.from(newSet) // ['a'.'b'.'c'] //ES6 new data structure --Set. It is similar to an array, but the member values are unique and not repeated. // It's easy to figure out how to do this. For example, if you want to deduplicate an array, it's much easier to do it with a Set. removeRepeatArray(arr) { //return [Array.from(arr)]
return [...new Set(arr)]
}Copy the code
find
The find method is used to find the first member of an array that meets the criteria. If no eligible member is found, underfind is returned
// The first member greater than 2 [1, 2, 3, 4]. Find ((n) => n > 2)//3Copy the code
findIndex
FindIndex method to find the index of the first qualified array member.
/ / the first members of larger than 2 index [1, 2, 3, 4]. FindIndex ((n) = > n > 2) / / 2Copy the code
includes
The includes method, which returns a Boolean value for whether an array contains the given value. If no eligible member is found, underfind is returned
[1, 2, 3].includes(2)//true
[1, 2, 3].includes(5)//false
[1, 2, NaN].includes(NaN)//trueCopy the code
9. Summary
Ok, so much for the common syntax of ES6 and its advantages over ES5, these are the ones I use more in my normal development. If you want to learn more about ES6, go to Ruan yifeng’s ECMAScript 6 Introduction. These grammars have taken up a large proportion in the development! Of course, if you have any good syntax, API recommendations, or think I wrote something wrong, write bad, welcome to give valuable advice, guidance. We also look forward to learning from each other and making progress together!
— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — want to know more, pay attention to focus on my WeChat public number: waiting for book cabinet