当前位置:网站首页>ES6 face test questions (reference documents)
ES6 face test questions (reference documents)
2022-04-23 17:50:00 【Front end more】
1、ES5、ES6 and ES2015 What's the difference? ?
ES2015Especially in2015New generation released inJSLanguage standards ,ES6The next generation JS Language standards , containES2015、ES2016、ES2017、ES2018etc. . At this stage, in most scenes ,ES2015Default equalsES6.ES5Generally speaking, it refers to the previous generation of language standards .ES2015It can be understood asES5andES6The time line
2、babel What is it? , What's the role ?
babelIt's aES6Transcoder , Can beES6The code changes toES5Code , To be compatible with those not yet supportedES6The platform of
3、let What's the usage? , With var Why use let?
stay
ES6Before , Declaration variables can only be used withvar,varIt's unreasonable to declare variables in a way , Accurately speaking , BecauseES5It's unreasonable not to have a block level scope inside . No block scope comes back with a lot of hard to understand problems , such asforloopvarVariable leakage , Variable coverage and so on .letDeclared variables have their own block level scope , And fixedvarVariable promotion caused by declaring variables .
4、 Give me a few ES6 Yes String Common upgrade optimization for string type ?
Optimization part
ES6Added string template , When splicing large strings , Use the backslash()` Instead of adding strings , Can keep all spaces and line breaks , Make string splicing look more intuitive , More elegant
Upgrade part
ES6stayStringThe prototype addedincludes()Method , What is used to replace tradition can only be usedindexOfFind methods that contain characters (indexOfreturn-1It's better toincludesMethod returnsfalseMore explicit , The meaning is clearer ), In addition, it addedstartsWith(),endsWith(),padStart(),padEnd(),repeat()Other methods , It can be easily used to find , Completion string
5、 Give me a few ES6 Yes Array Common upgrade and optimization of array type
Optimization part
- Array deconstruction assignment .
ES6You can uselet [a,b,c] = [1,2,3]Form to assign variables , When declaring more variables , Don't write a lot morelet(var),And the mapping is clear , And support to assign default value - Extension operator .
ES6New extension operator (...)( important ), It can easily transform array and loose sequence , Can replaceargumentsObjects andapplyMethod , It is easy to get the parameter set in the case of unknown parameter number .( Especially inES5in ,argumentsIt's not a real array , It's an array like object , But the inverse operation of the extension operator can return a real array ). Extended operators can also easily and easily achieve array copy and deconstruction assignment (let a = [2,3,4];let b = [...a])
Upgrade part
ES6stayArrayThe prototype addedfind()Method , What is used to replace tradition can only be usedindexOfFind methods that contain array items , And fixedindexOfCan't findNaN Of bug([NaN].indexOf(NaN) === -1). In addition, it addedcopyWithin(),includes(),fill(),flat()Other methods , It can be used to find strings conveniently , completion , Conversion, etc
6、 Give me a few ES6 Yes Number Commonly used upgrading and optimization of digital type
Optimization part
ES6 stay
NumberThe prototype addedisFinite(),isNaN()Method , To replace the traditional globalisFinite(),isNaN()Method to detect whether the value is limited 、 Whether it isNaN.ES5OfisFinite(),isNaN()Methods first convert non numeric parameters toNumberMake a judgment about the type , This is not reasonable , Most of all isNaN('NaN') === trueThe strange behavior of--'NaN'Is a string , howeverisNaNBut this isNaN. andNumber.isFinite()andNumber.isNaN()Then there will be no such problem (Number.isNaN('NaN') === false).(isFinite()ditto )
Upgrade part
ES6stayMathObject addedMath.cbrt(),trunc(),hypot()And so on many scientific counting methods , Can be more comprehensive cube root 、 Sum cube root and so on
7、 Give me a few ES6 Yes Object Common upgrade optimization done by type ?( important )
Optimization part
Object property variable declaration .
ES6Object properties or methods can be declared directly as variables ,. More concise than the traditional key value pair formal declaration , It is more convenient , Semantic clarity
let [apple, orange] = ['red appe', 'yellow orange'];
let myFruits = {
apple, orange}; // let myFruits = {apple: 'red appe', orange: 'yellow orange'};
Especially in object deconstruction assignment ( See optimization b.) Or when the module outputs variables , The benefits of this style of writing are most obvious
let {
keys, values, entries} = Object;
let MyOwnMethods = {
keys, values, entries}; // let MyOwnMethods = {keys: keys, values: values, entries: entries}
You can see that attribute variable declaration attributes look more concise . It can also be written in a simple way
let es5Fun = {
method: function(){
}
};
let es6Fun = {
method(){
}
}
Object's deconstruction assignment .
ES6Objects can also be like array unmarshalling assignments , To deconstruct and assign variables
let {
apple, orange} = {
apple: 'red appe', orange: 'yellow orange'};
Object's extension operator (
...). ES6 The extension operator of an object is essentially the same as that of an array , After all, arrays are special objects . One of the most common and best uses of the object's extension operator is that it can easily take out all or part of the traversable properties inside a target object , So as to merge and decompose objects
let {
apple, orange, ...otherFruits} = {
apple: 'red apple', orange: 'yellow orange', grape: 'purple grape', peach: 'sweet peach'};
// otherFruits {grape: 'purple grape', peach: 'sweet peach'}
// Be careful : Object extension operators are used to deconstruct assignments , The extension operator can only be used with the most one parameter (otherFruits No more parameters )
let moreFruits = {
watermelon: 'nice watermelon'};
let allFruits = {
apple, orange, ...otherFruits, ...moreFruits};
superkeyword .ES6stayClassClass is added similar tothisKey words ofsuper. Same asthisAlways points to different objects in the current function ,superKeyword always points to the prototype object of the current function
Upgrade part
ES6` stay `Object` The prototype added `is()` Method , Make an equal comparison between two target objects , To perfect `'==='` Method .`'==='` In the method `NaN === NaN //false` In fact, it is unreasonable ,`Object.is` Fixed this little `bug`.`(Object.is(NaN, NaN) // true)
ES6stayObjectThe prototype addedassign()Method , Used for adding properties to objects or merging multiple objects
const target = {
a: 1 };
const source1 = {
b: 2 };
const source2 = {
c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
Be careful :
assignMerged objectstargetCan only mergesource1、source2The self property of , It's not going to mergesource1、source2Inheritance properties in , It also doesn't merge properties that can't be enumerated , And can't copy correctly get and set attribute ( Will directly executeget/setfunction , takereturnValue )
ES6stayObjectThe prototype addedgetOwnPropertyDescriptors()Method , This method enhancesES5ingetOwnPropertyDescriptor()Method , You can get the description object of all the properties of the specified object . combinationdefineProperties()Method , Perfect for copying objects , Including copyinggetandsetattributeES6stayObjectThe prototype addedgetPrototypeOf()andsetPrototypeOf()Method , Used to get or set the current objectprototypeobject . The significance of this method lies in ,ES5Get settingsprototypeYes, like through__proto__Property to implement , However__proto__Attributes are not ES The attributes specified in the specification , It 's just browser manufacturers “ Privately ” Added properties , It's just that it's used by default because of its wide application , In a non browser environment, it doesn't necessarily work , So for the sake of security , Gets or sets the... Of the current objectprototypeObject time , All should adopt ES6 New standard usageES6stayObjectThere's something new on the prototypeObject.keys(),Object.values(),Object.entries()Method , All the keys used to get the object 、 All values and all key value pairs array
8、 Give me a few ES6 Yes Function Common upgrade optimization of function types ?
Optimization part
Arrow function ( The core ). The arrow function is ES6 One of the core upgrades , There is no arrow function of its own this, This has changed the past JS The most incomprehensible of functions this Operating mechanism . Main optimization points
- In the arrow function this Point to the object where the function is defined , Instead of the object the function is executed on .ES5 Function this Always point to the object where the function is executed , This makes in many cases
thisIt's hard to understand , Especially in the case of non strict mode ,thisSometimes it points to global objects , This can even be attributed to the language level bug One of .ES6 The arrow function of optimizes this , It doesn't have its own insidethis, This leads tothisAlways pointing to the next levelthis, If the upper level is still an arrow function , Keep pointing up , Until you point to having yourselfthisSo far , And as your ownthis - Arrow functions cannot be used as constructors , Because it doesn't have its own
this, Cannot instantiate - It's also because the arrow function doesn't have its own this, So arrow function There is no such thing as
argumentsobject .( You can use extension operators instead of ) - Function default assignment .
ES6Before , The parameter of a function cannot be given a default value , It can only be implemented inside a function through workarounds .ES6Make the function default assignment in a more concise and clear way
function es6Fuc (x, y = 'default') {
console.log(x, y);
}
es6Fuc(4) // 4, default
Upgrade part
ES6 Added double colon operator , To replace the old
bind,call, andapply.( Browser does not support ,BabelTranscoding is already supported )
foo::bar;
// Equate to
bar.bind(foo);
foo::bar(...arguments);
// Equate to
bar.apply(foo, arguments);
9、Symbol What is it? , What's the role ?
SymbolyesES6The seventh type of raw data introduced ( The statement is not accurate , It should be the seventh data type ,Object Not one of the original data types , Corrected ), all Symbol() The generated values are unique , It can fundamentally solve the problem that too many object properties lead to conflicting coverage of property names . In the objectSymbol()Property cannot befor...inTraverse , But it's not a private property either
10、Set What is it? , What's the role ?
SetyesES6The introduction of a similarArrayNew data structure of ,SetThe members of an instance are similar to arraysitemmember , The difference is thatSetThe members of the instance are all unique , Not repeated . This feature can easily implement array de duplication
11、Map What is it? , What's the role ?
MapyesES6The introduction of a similarObjectNew data structure of ,MapIt can be understood asObjectSuperset , It breaks the traditional definition of objects in the form of key value pairs , Object'skeyNo longer limited to strings , It can also beObject. It can describe the properties of objects more comprehensively
12、Proxy What is it? , What's the role ?
Proxy` yes `ES6` A new constructor , It can be understood as JS An agent of language , To change JS Some of the default language behaviors , Including intercepting the default `get/set` Wait for the bottom method , bring JS More freedom of use , It can meet the needs of developers to the greatest extent . For example, by intercepting objects `get/set` Method , You can easily customize what you want `key` perhaps `value`. The following example shows , Define any one `myOwnObj` Of `key`, Can become their own functions
function createMyOwnObj() {
// Want to put all of key All become functions , perhaps Promise, perhaps anything
return new Proxy({
}, {
get(target, propKey, receiver) {
return new Promise((resolve, reject) => {
setTimeout(() => {
let randomBoolean = Math.random() > 0.5;
let Message;
if (randomBoolean) {
Message = ` Yours ${
propKey} Good luck. , succeed `;
resolve(Message);
} else {
Message = ` Yours ${
propKey} No luck , failed `;
reject(Message);
}
}, 1000);
});
}
});
}
let myOwnObj = createMyOwnObj();
myOwnObj.hahaha.then(result => {
console.log(result) // Yours hahaha Good luck. , succeed
}).catch(error => {
console.log(error) // Yours hahaha No luck , failed
})
myOwnObj.wuwuwu.then(result => {
console.log(result) // Yours wuwuwu Good luck. , succeed
}).catch(error => {
console.log(error) // Yours wuwuwu No luck , failed
})
13、Reflect What is it? , What's the role ?
Reflect` yes `ES6` A new object introduced , There are two main functions of him , One is to distribute some of the original scattered in `Object`、`Function` Or methods in global functions ( Such as `apply`、`delete`、`get`、`set` wait ), To integrate into `Reflect` On , In this way, it can be more convenient and unified to manage some of the original `API`. The second is because `Proxy` Can override default native API, If once original `API` Don't rewrite, you may not find , therefore `Reflect` It can also backup the original API The role of , So that even if the original `API` After being rewritten , Can also be rewritten after `API` Use the default `API
14、Promise What is it? , What's the role ?
PromiseyesES6A new object introduced , His main function is to solve JS Asynchronous mechanism , The callback mechanism produces “ Back to hell ”. It's not a breakthroughAPI, It just encapsulates the asynchronous callback form , Make asynchronous callbacks more elegant to write , More readable , And can chain call
15、Iterator What is it? , What's the role ?( important )
IteratoryesES6One of the most important concepts , It's not the object , It's not any kind of data type . becauseES6AddedSet、Maptype , They andArray、ObjectThe type is very similar ,Array、ObjectIt can be traversed , howeverSet、MapCan't use for Loop traversal , There are two solutions to this problem , One is forSet、MapAdd a new one for traversalAPI, The other is forSet、Map、Array、ObjectAdd a uniform traversalAPI, obviously , The second is better ,ES6It also needs a design standard to let it go , To unify the traversal methods of all traversable types .IteratorIt is such a standard . Or a normative idea- It's like
JavaScriptyesECMAScriptA specific implementation of the standard is the same ,IteratorThe specific implementation of the standard isIteratorIterator .IteratorThe standard stipulates , All deployedkeyThe value is[Symbol.iterator], And[Symbol.iterator]OfvalueIt's standardIteratorThe interface function ( The standardIteratorThe interface function : This function must return an object , And the object containsnextMethod , And executenext()Can return includevalue/doneAttributeIteratorobject ) The object of , They are called traversable objects ,next()After the return ofIteratorThe object isIteratorIterator
//obj It's ergodic , Because it follows Iterator standard , And contains [Symbol.iterator] Method , The method functions also conform to the standard Iterator The interface specification .
//obj.[Symbol.iterator]() Namely Iterator Iterator
let obj = {
data: [ 'hello', 'world' ],
[Symbol.iterator]() {
const self = this;
let index = 0;
return {
next() {
if (index < self.data.length) {
return {
value: self.data[index++],
done: false
};
} else {
return {
value: undefined, done: true };
}
}
};
}
};
ES6toSet、Map、Array、StringAll added[Symbol.iterator]Method , And[Symbol.iterator]The method functions also conform to the standardIteratorThe interface specification , thereforeSet、Map、Array、StringBy default, it can be traversed
//Array
let array = ['red', 'green', 'blue'];
array[Symbol.iterator]() //Iterator Iterator
array[Symbol.iterator]().next() //{value: "red", done: false}
//String
let string = '1122334455';
string[Symbol.iterator]() //Iterator Iterator
string[Symbol.iterator]().next() //{value: "1", done: false}
//set
let set = new Set(['red', 'green', 'blue']);
set[Symbol.iterator]() //Iterator Iterator
set[Symbol.iterator]().next() //{value: "red", done: false}
//Map
let map = new Map();
let obj= {
map: 'map'};
map.set(obj, 'mapValue');
map[Symbol.iterator]().next() {
value: Array(2), done: false}
16、for…in and for…of What's the difference? ?
If you see question 16 , So it's a good answer . Question 16 refers to ES6 Unified traversal standard , Made traversable objects , So how to traverse it ? The answer is to use
for...of.ES6 Regulations , It's been deployedIteratorObject of the interface ( Traversable objects ) Both can passfor...ofTo traverse the , andfor..inOnly objects can be traversed
- That means , Arrays can also be used
for...ofTraverse , This greatly facilitates the value of the array , And avoid a lot of proceduresfor..inThe bad habit of traversing arrays
17、Generator What is a function , What's the role ?
- if
JavaScriptyesECMAScriptA concrete realization of the standard 、IteratorErgodic isIteratorThe concrete realization of , thatGeneratorFunction can be said to beIteratorSpecific implementation of the interface . - perform
GeneratorFunction returns a traverser object , every timeGeneratorInside the functionyieldAll of them are equal to thenext()Method , And throughnext(value)Method passed in custom value, To changeGeneratorBehavior of functions . GeneratorFunctions can be matched byThunkFunctions make asynchronous programming and control flow management easier and more elegant .
18、async What is a function , What's the role ?
asyncFunctions can be interpreted as built-in automatic actuatorsGeneratorFunction grammar sugar , It matchesES6OfPromiseAlmost perfect implementation of asynchronous programming solutions
19、Class、extends What is it? , What's the role ?
ES6OfclassCan be seen as just aES5Generate the syntax sugar of the instance object's constructor . It refers tojavaLanguage , Defines the concept of a class , Make the object prototype more clear , Object instantiation is more like object-oriented programming .ClassClass can pass throughextendsImplementation inheritance . It and ES5 The difference between constructors
All methods defined within the class , It's all inestimable
///ES5
function ES5Fun (x, y) {
this.x = x;
this.y = y;
}
ES5Fun.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
}
var p = new ES5Fun(1, 3);
p.toString();
Object.keys(ES5Fun.prototype); //['toString']
//ES6
class ES6Fun {
constructor (x, y) {
this.x = x;
this.y = y;
}
toString () {
return '(' + this.x + ', ' + this.y + ')';
}
}
Object.keys(ES6Fun.prototype); //[]
ES6OfclassClass must usenewThe command operation , andES5The constructor of does not usenewIt can also be executed .ES6OfclassClass does not have variable Promotion , Must be defined firstclassThen instantiate , UnlikeES5Constructor can be written after instantiation .ES5Inheritance , The essence is to create the instance object of the subclass firstthis, Then add the method of the parent class tothisabove .ES6The inheritance mechanism is quite different , The essence is to first instance the parent class object's properties and methods , Add tothisabove ( So you have to call it firstsuperMethod ), And then modify it with the constructor of the subclassthis.
20、module、export、import What is it? , What's the role ?
module、export、importyesES6It is used to unify the design idea and implementation scheme of front-end modularization scheme .export、importThe emergence of a unified front-end modular implementation , Integration standardizes browsers / The modularization method of the server , To replace the traditionalAMD/CMD、requireJS、seaJS、commondJSAnd a series of different front-end modules , Make the front-end modularization more unified ,JSCan also be more able to achieve large-scale application development .importThe introduced module is static loading ( Load during compilation ) Instead of dynamic loading ( Load at run time ).importintroduceexportThe exported interface value is a dynamic binding relationship , Through this interface , It can get the real-time value inside the module
21、 In daily front-end code development , What are worth using ES6 To improve programming optimization or specification ?
- Use arrow function instead of
var self = this; How to do it . - Commonly used
letreplacevarcommand . - Common arrays / Object to name variables , Structure is clearer , The meaning is clearer , Better readability .
- In the case of long string multivariable combination , Replace string accumulation with template string , Can achieve better results and reading experience .
- use
ClassClass to replace the traditional constructor , The next generation is the instantiation object . - In large application development , To maintain
moduleModular development thinking , Distinguish the relationship between modules , Commonly usedimport、exportMethod .
22、ES6 Understanding
New template string ( by JavaScript Provides a simple string interpolation function )、 Arrow function ( The left side of the operator is the input parameter , On the right is the operation performed and the value returned Inputs=>outputs.)、for-of( To traverse data — For example, the value in the array .)arguments Object can be perfectly replaced by indefinite parameters and default parameters .ES6 take promise Objects are included in the specification , Native is provided Promise object . Added let and const command , Used to declare variables . Added block level scope .let The command actually adds block level scope .ES6 Regulations ,var Command and function Global variables declared by the command , Properties that belong to global objects ;let command 、const command 、class Global variables declared by the command , Properties that do not belong to global objects .. There is also the introduction of module The concept of modules
23、 Tell me about your right Promise The understanding of the
- according to Promise/A+ The definition of ,Promise There are four states :
- pending: The initial state , Not fulfilled or rejected.
- fulfilled: Successful operation .
- rejected: Failed operation .
- settled: Promise Has been fulfilled or rejected, It's not pending
- in addition , fulfilled And rejected Together, they are called settled
- Promise Object is used to delay (deferred) And asynchronous (asynchronous ) Calculation
24、Promise Constructor for
- Construct a Promise, The basic usage is as follows :
var promise = new Promise(function(resolve, reject) {
if (...) {
// succeed
resolve(result);
} else {
// fails
reject(Error(errMessage));
}
});
- Promise Instance has then Method ( have then Object of method , Usually called thenable). Its usage is as follows :
promise.then(onFulfilled, onRejected)
- Take two functions as arguments , In a fulfilled Is called when , In a rejected Is called when , The received parameter is future,onFulfilled Corresponding resolve, onRejected Corresponding reject
What is? Promise ?
- Promise It's an object , Used to represent and pass the final result of asynchronous operation
- Promise The main way of interaction : Pass the callback function into then Method to get the final result or the cause of the error
- Promise Performance in code writing : With “ call chaining ” Instead of the callback function, it is nested layer by layer ( Back to hell )
Deconstruct assignment :
As long as it is determined that the patterns on both sides of the equal sign are the same ( deconstruction ), The variable on the left is given the corresponding value ( assignment ), Assign a value to a variable at a time , Deconstruction assignment can assign values to multiple variables at one time .
25、 Talk about what you know ECMAScript6 New features ?
- Block level action area
let a = 1; - You can define constants
const PI = 3.141592654; - Variable deconstruction assignment
var [a, b, c] = [1, 2, 3]; - String extension ( Template string )
var sum =${a + b}; - Extension of arrays ( Convert array type )
Array.from($('li')); - Function extension ( Extension operator )
[1, 2].push(...[3, 4, 5]); - Object extension ( Equal value algorithm )
Object.is(NaN, NaN); - New data type (Symbol)
let uid = Symbol('uid'); - New data structure (Map)
let set = new Set([1, 2, 2, 3]); - for…of loop
for(let val of arr){}; - Promise object
var promise = new Promise(func); - Generator function
function* foo(x){yield x; return x*x;} - introduce Class( class )
class Foo {} - Introduce module system
export default func; - introduce async function [ES7]
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value)
}
26、Object.is() Compared with the original comparison operator =、 The difference between ?
- == Equality operator , Data type conversion will be performed automatically during comparison
- === Strict equality operator , Compare without implicit type conversion
- Object.is Equal value algorithm , stay === On the basis of 0 and NaN Special treatment
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value)
}
27、 What is? Babel
- Babel It's a JS compiler , Bring your own set ES6 Grammar Converter , Used to transform JS Code .
These converters allow developers to use the latest in advance JS grammar (ES6/ES7), Instead of waiting for the browser to be fully compatible . - Babel Only new is converted by default JS syntax (syntax), Instead of converting new ones API.
版权声明
本文为[Front end more]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230550117873.html
边栏推荐
- 122. The best time to buy and sell stocks II - one-time traversal
- Where is the configuration file of tidb server?
- 嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?
- 常用SQL语句总结
- ECMAScript history
- Kubernetes 服务发现 监控Endpoints
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- Ouvrir des contrats à terme, ouvrir des comptes en nuage ou faire confiance aux logiciels des sociétés à terme?
- MySQL advanced index [classification, performance analysis, use, design principles]
- 470. Rand10() is implemented with rand7()
猜你喜欢

Comparison between xtask and kotlin coroutine
![SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]](/img/60/e4d47d458dd98a0c6ba51874e07c30.png)
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]

C1小笔记【任务训练篇二】

QT modification UI does not take effect

48. Rotate image

470. Rand10() is implemented with rand7()

STM32 entry development board choose wildfire or punctual atom?

Detailed deployment of flask project

Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory

2021长城杯WP
随机推荐
Open futures, open an account, cloud security or trust the software of futures companies?
Open source key component multi_ Button use, including test engineering
STM32 entry development board choose wildfire or punctual atom?
列錶的使用-增删改查
Where is the configuration file of tidb server?
Add drag and drop function to El dialog
2022年茶艺师(初级)考试模拟100题及模拟考试
Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
102. 二叉树的层序遍历
油猴网站地址
一些问题一些问题一些问题一些问题
Land cover / use data product download
Tdan over half
2022 Shanghai safety officer C certificate operation certificate examination question bank and simulation examination
Client example analysis of easymodbustcp
Advantages and disadvantages of several note taking software
HCIP第五次实验
开源按键组件Multi_Button的使用,含测试工程
In JS, t, = > Analysis of
Submit local warehouse and synchronize code cloud warehouse