Xiaomi company JavaScript interview questions, Xiaomi javascript
Interview Questions
I,
Copy codeThe Code is as follows:
Define such a function
Function repeat (func, times, wait ){
}
This function can return a new function, for example
Var repeatedFun = repeat (alert, 10,500 0)
Call this repeatedFun ("hellworld ")
Alert ten helloworld requests, with an interval of 5 seconds
II,
Copy codeThe Code is as follows:
Write a function stringconcat, required
Var result1 = stringconcat ("a", "B") result1 = "a + B"
Var stringconcatWithPrefix = stringconcat. prefix ("hellworld ");
Var result2 = stringconcatWithPrefix ("a", "B") result2 = "hellworld + a + B"
Food Solution
These two questions are taken into consideration by the closure. If you don't talk much about it, go directly to the code.
Copy codeThe Code is as follows:
/**
* Question 1
* @ Param func
* @ Param times
* @ Param wait
* @ Returns {repeatImpl}
*/
Function repeat (func, times, wait ){
// Anonymous functions are not needed for debugging convenience.
Function repeatImpl (){
Var handle,
_ Arguments = arguments,
I = 0;
Handle = setInterval (function (){
I = I + 1;
// Cancel the timer when the specified number of times is reached
If (I = times ){
ClearInterval (handle );
Return;
}
Func. apply (null, _ arguments );
}, Wait );
}
Return repeatImpl;
}
// Test case
Var repeatFun = repeat (alert, 4, 3000 );
RepeatFun ("hellworld ");
/**
* Question 2
* @ Returns {string}
*/
Function stringconcat (){
Var result = [];
Stringconcat. merge. call (null, result, arguments );
Return result. join ("+ ");
}
Stringconcat. prefix = function (){
Var _ arguments = [],
_ This = this;
_ This. merge. call (null, _ arguments, arguments );
Return function (){
Var _ args = _ arguments. slice (0 );
_ This. merge. call (null, _ args, arguments );
Return _ this. apply (null, _ args );
};
};
Stringconcat. merge = function (array, arrayLike ){
Var I = 0;
For (I = 0; I <arrayLike. length; I ++ ){
Array. push (arrayLike [I]);
}
}
// Test case
Var result1 = stringconcat ("a", "B"); // result1 = "a + B"
Var result3 = stringconcat ("c", "d"); // result1 = "a + B"
Var stringconcatWithPrefix = stringconcat. prefix ("hellworld ");
Var stringconcatWithPrefix1 = stringconcat. prefix ("hellworld1 ");
Var result2 = stringconcatWithPrefix ("a", "B"); // result2 = "hellworld + a + B"
Var result4 = stringconcatWithPrefix1 ("c", "d"); // result2 = "hellworld + a + B"
Alert (result1 );
Alert (result2 );
Alert (result3 );
Alert (result4 );