Demand has changed to live has been added, overtime overnight to see the morning glow. Finally, the line has been postponed, the bug is still not over.
Interview rocket, screw work, although I only want to screw, but I need to use rocket technology to search for the screw work, how can you during the interview process in unbeaten point, brush the topic is a good shortcut, today will summarize some of the more classic interview question has carried on the summary, share with you.
All the topics in this article were first published in the public number [front end some play], xiaobian will sort out two interview questions every day, and then push to all friends, pay attention to xiaobian, take you to brush interview questions every day, do not want to be salty fish, want to change jobs, still hesitant, pay attention to the offer of big factory.
Subject to a
Subject to introduce
Please improve the sum function so that the sum(1,2,3,4,5,6) function returns 21. AsyncAdd function needs to be called in the sum function for numerical calculation, and asyncAdd function cannot be modified
/** * Call this function in the sum function to complete the numerical calculation *@param {*} The first value of a to add, star@param {*} The second value of b that I'm going to add, star@param {*} The callback function */ after the callback is added
function asyncAdd(a,b,callback) {
setTimeout(function(){
callback(null, a+b)
},1000)}/** * Call asyncAdd in this method to complete the numerical calculation *@param {... any} Rest passes in the argument */
async function sum(. rest) {
// Please complete the code here
}
let start = window.performance.now()
sum(1.2.3.4.5.6).then(res= > {
Make sure that after calling sum, the result 21 is returned
console.log(res)
console.log('Total time of program execution:The ${window.performance.now() - start}`)})Copy the code
The problem can be divided into three levels of difficulty according to the output time of the program
- Bronze difficulty, output time is greater than 6 seconds
- Silver difficulty, the output time is greater than 3 seconds
- On King difficulty, the output time is greater than 1 second
The answer
- Bronze is difficult
async function sum(. rest) {
// Take out the first value as the initial value
let result = rest.shift()
// Iterate over rest with "for of"
for(let num of rest) {
// Use promise to get the sum result
result = await new Promise(resolve= > {
asyncAdd(result, num, (_,res) = > {
resolve(res)
})
})
}
// Returns the execution result
return result
}
// The execution succeeds, and the execution duration is longer than 6 seconds
sum1(1.2.3.4.5.6).then(res= > {
console.log('The calculation result is:${res}`)})Copy the code
- Silver is difficult
In bronze, we add each item in the array. However, some optimizations can also be made to execute multiple executions concurrently, such as sum(1,2,3,4,5,6), which can be executed simultaneously with 1+2,3+4,5+6 to improve execution efficiency
async function sum(. rest) {
// If less than two values are passed, return directly
if (rest.length <= 1) {
return rest[0] | |0
}
const promises = []
// Execute the array in pairs
for (let i = 0; i < rest.length; i += 2) {
promises.push(
new Promise(resolve= > {
// If rest[I +1] is undefined, the array length is odd, this is the last one
if (rest[i + 1= = =undefined) {
resolve(rest[i])
} else {
// Call asyncAdd to calculate
asyncAdd(rest[i], rest[i + 1].(_, result) = > {
resolve(result)
})
}
})
)
}
// get the result of the first calculation
const result = await Promise.all(promises)
// then we call sum again for the first result [3,7,11]
return awaitsum(... result) }// The execution is successful, and the execution duration is longer than 3 seconds but less than 4 seconds
sum1(1.2.3.4.5.6).then(res= > {
console.log('The calculation result is:${res}`)})Copy the code
- The king is difficult
async function sum(. rest) {
let result = 0
// Implicit conversion, object + number, calls the toString method of the object first
const obj = {}
obj.toString = function() {
return result
}
const promises = []
for(let num of rest) {
promises.push(new Promise((resolve) = > {
asyncAdd(obj, num, (_, res) = > {
resolve(res)
})
}).then(res= > {
// After the result value is changed, the return value of obj.toString is changed, and the next setTimeout call uses the new value
result = res
}))
}
await Promise.all(promises)
return result
}
// The execution succeeds. The execution duration is longer than 1 second but less than 2 seconds
sum1(1.2.3.4.5.6).then(res= > {
console.log('The calculation result is:${res}`)})Copy the code
Because JS is executed in a single thread, in the above code, we put all the calculations into promises array in for of, and then execute them in one go through promise.all without considering which two numbers to add first. Because of the single-threaded nature, we can guarantee that each Promise is executed in sequence, and that the return value of obj. ToString is the return value of the previous Promise
Topic 2
Subject to introduce
What does the following code output?
console.log(typeof (() = > {}))
console.log(typeof ['Front end has play'.'Public Account'])
console.log(typeof null)
console.log(typeof undefined)
console.log(typeof Function.prototype)
console.log('zijun' instanceof String)
console.log(new Date(a)instanceof Date)
Copy the code
The answer
/ / output function
console.log(typeof (() = > {}))
/ / output object
console.log(typeof ['Front end has play'.'Public Account'])
/ / output object
console.log(typeof null)
/ / output is undefined
console.log(typeof undefined)
/ / output function
console.log(typeof Function.prototype)
/ / output is false
console.log('zijun' instanceof String)
/ / output true
console.log(new Date(a)instanceof Date)
Copy the code
Note that for Typeof, all primitive types except null are correctly judged, while for reference types, all but functions are judged object.
With Instanceof, you cannot determine the base type, but you can correctly determine the reference type
The title three
Subject to introduce
Implement an Instanceof to make the following code work
/** Custom instanceof */
function instanceOf(left, right) {
// Please improve the following code, can not use native instanceof
}
class A{}
class B extends A {}
class C{}
const b = new B()
/ / output true
console.log(instanceOf(b,B))
/ / output true
console.log(instanceOf(b,A))
/ / output is false
console.log(instanceOf(b,C))
Copy the code
The answer
In this case, the judgment principle of instanceof is mainly investigated. The main realization principle of Instanceof is that as long as the prototype of the right variable is on the prototype chain of the left variable. Thus, Instanceof iterates through the prototype chain of the left variable until it finds the prototype of the right variable and returns false if the lookup fails.
/** Custom instanceof */
function instanceOf(left, right) {
let proto = left.__proto__
while(proto){
if(proto === right.prototype){
return true
}
proto = proto.__proto__
}
return false
}
class A{}
class B extends A {}
class C{}
const b = new B()
/ / output true
console.log(instanceOf(b,B))
/ / output true
console.log(instanceOf(b,A))
/ / output is false
console.log(instanceOf(b,C))
Copy the code
The title four
Subject to introduce
Simulate implementing the new operator to make the following code work
function myNew(constructor, ... rest) {
// Please improve the code here, do not use the new operator directly
}
function Fun(name,sex) {
this.name = name
this.sex = sex
}
Fun.prototype.getUserInfo = function() {
return 'My nameThe ${this.name}My genderThe ${this.sex}`
}
const fun = myNew(Fun,'zijun'.'male')
// My name is Zijun and my gender is male
console.log(fun.getUserInfo())
Copy the code
The answer
Call the constructor using the new operator
- Create a new object;
- Assign the scope of the constructor to the new object;
- Execute the code in the constructor;
- Returns a new object;
function myNew(constructor, ... rest) {
if (typeof constructor! = = 'function') {
return constructor;
}
// Create a new object, associated with the constructor's prototype object
const _constructor = Object.create(constructor.prototype);
// Execute the constructor
const obj = constructor.apply(_constructor, rest);
// Return the result of the constructor execution if the result is an object
if (typeof obj === 'object') {
return obj;
} else {
return_constructor; }}function Fun(name,sex) {
this.name = name
this.sex = sex
}
Fun.prototype.getUserInfo = function() {
return 'My nameThe ${this.name}My genderThe ${this.sex}`
}
const fun = myNew(Fun,'zijun'.'male')
// My name is Zijun and my gender is male
console.log(fun.getUserInfo())
Copy the code
Topic five
Subject to introduce
Say the following code output
const a = {}
const b = Symbol('1')
const c = Symbol('1')
a[b] = 'zijun'
a[c] = 'gentlemen'
// Am I a zijun or a gentleman
console.log(a[b])
const d = {}
const e = {key: '1'}
const f = {key: '2'}
d[e] = 'zijun'
d[f] = 'gentlemen'
// Am I a zijun or a gentleman
console.log(d[e])
Copy the code
The answer
const a = {}
const b = Symbol('1')
const c = Symbol('1')
a[b] = 'zijun'
a[c] = 'gentlemen'
// Output child
console.log(a[b])
const d = {}
const e = {key: '1'}
const f = {key: '2'}
d[e] = 'zijun'
d[f] = 'gentlemen'
// Output gentleman
console.log(d[e])
Copy the code
For the first output, the Symbol() function returns a value of type ** “Symbol” **. The Symbol function passes arguments only for identification and does not affect the uniqueness of the value
For the second output, since e and f are both objects, and the key of the object can only be a number or a character, the object is converted to a character. The toString method of the object returns object object, and all output is gentleman
Topic 6
Subject to introduce
Say what the following code outputs
console.log([] + [])
console.log({} + [])
console.log([] == ! [])console.log(true + false)
Copy the code
The answer
- First line of code
// Outputs "" empty string console.log([] + [])Copy the code
This line of code outputs an empty string “”, and when the wrapper type is evaluated, valueOf is called first. If valueOf returns the wrapper type again, toString is called
Const val = [].valueof () const val = [].valueof () const val = [].valueof () For example, [1,2,3].tosting becomes "1,2,3" and the empty array toString is an empty string const val1 = val.tostring () // val1 is an empty stringCopy the code
So the code above is equivalent to
console.log("" + "")
Copy the code
-
Second line of code
Console. log({} + [])Copy the code
As in the first question, {} is converted to [object object] and then added to “”
-
Line 3
// Print true console.log([] ==! [])Copy the code
For ===, the values are strictly compared, but not for ==
So for the above code, take a look at the following step by step analysis
// This outputs false console.log(! Log (Number(false)) // Wrapper type and base type == First wrapper type is converted to base type by valueOf toString // "Console.log ([].toString())) // To apply the second rule, convert the empty string to a numeric value, // print 0 console.log(Number("")) // so console.log(0 == 0)Copy the code
-
- Such as
null == undefined
- If the
number
withnumber
The comparison will convert it tonumber
- If one of the parties being compared is
boolean
, then will firstboolean
convertnumber
- Such as
-
Line 4
// Output 1 console.log(true + false)Copy the code
Two basic types are added, if one of them is a character, the others are converted to a character addition, otherwise the type is converted to Number, then added, Number(true) is 1, Number(false) is 0, so the result is 1
All the topics in this article were first published in the public number [front end some play], xiaobian will sort out two interview questions every day, and then push to all friends, pay attention to xiaobian, take you to brush interview questions every day, do not want to be salty fish, want to change jobs, still hesitant, pay attention to the offer of big factory.
conclusion
Don’t blow out your inspiration and your imagination; Don’t be a slave to your model. — Vincent Van Gogh