directory
1. Array sort.
2. Array element decrement;
3. Use recursive method to find the array summation;
4. The idea of anti-shake throttling.
5. Deep copy and shallow copy;
6. Do a 10-second countdown;
7. Use and differences between setTimeout() and setInterval()
Some common front-end interviewers ask candidates to write programming questions
1. Array sort.
The sort() method sorts arrays alphabetically
var fruits = ["Banana"."Orange"."Apple"."Mango"];
fruits.sort();
Copy the code
Use the same technique to sort arrays in descending order:
var points = [40.100.1.5.25.10];
points.sort(function(a, b){return b - a});
Copy the code
2. Array element decrement;
Use ES6 Set to remove weights (most commonly used in ES6)
function unique (arr) {
return Array.from(new Set(arr))
}
var arr = [1.1.'true'.'true'.true.true.15.15.false.false.undefined.undefined.null.null.NaN.NaN.'NaN'.0.0.'a'.'a', {}, {}];console.log(unique(arr))
//[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]
Copy the code
Use for to nest for and then splice to deduplicate it
function unique(arr){
for(var i=0; i<arr.length; i++){
for(var j=i+1; j<arr.length; j++){
if(arr[i]==arr[j]){ // The first is the same as the second, and the splice method deletes the second
arr.splice(j,1); j--; }}}return arr;
}
var arr = [1.1.'true'.'true'.true.true.15.15.false.false.undefined.undefined.null.null.NaN.NaN.'NaN'.0.0.'a'.'a', {}, {}];console.log(unique(arr))
/ / (1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", {...}, {...}] / / NaN and {} not to heavy, two null directly disappeared
Copy the code
More array to heavy: segmentfault.com/a/119000001…
3. Use recursive method to find the array summation;
recursive
var arr = [1.2.3];
function sum(arr) {
if(arr.length == 0) {return 0;
} else if (arr.length == 1) {return arr[0];
} else {
return arr[0] + sum(arr.slice(1)); }}console.log(sum(arr));/ / 6
Copy the code
The for loop
var arr = [1.2.3];
function sum(arr) {
var s = 0;
for (var i = 0; i<arr.length; i++) { s += arr[i]; }return s;
}
console.log(sum(arr));/ / 6
Copy the code
4. The idea of anti-shake throttling.
Image stabilization
Function debounce means that after an event is triggered, a function can only be executed once within n seconds. If an event is triggered within n seconds, the function delay time is recalculated.
For example: when taking the elevator, if the elevator detects that someone comes in (trigger event), it will wait 10 seconds longer. At this time, if someone comes in (trigger event within 10 seconds), the elevator will wait 10 seconds longer. In the above example, the elevator does not close the door until it detects someone entering for 10 seconds, so the key to “function stabilization” is to wait a certain amount of time after an event has occurred before performing a specific action.
The main point of function stabilization is that a setTimeout is needed to assist the implementation and delay the execution of the required code. If the method fires more than once, clear the last recorded delay with clearTimeout and restart the timer. If the event is not retriggered during the timing, the object code will be executed after the delay time is finished.
function debounce(fn,wait){
var timer = null;
return function(){
if(timer ! = =null) {clearTimeout(timer);
}
timer = setTimeout(fn,wait); }}function handle(){
console.log(Math.random());
}
window.addEventListener("resize",debounce(handle,1000));
Copy the code
The throttle
Function throttling: Ensures that event handlers are called only once in a certain period of time when events are continuously emitted. Throttling popular explanation is like our tap water, as soon as the valve is opened, the water pouring down, holding the good traditional virtue of thrift, we have to turn the tap down a little, it is best to be as we will according to a certain rule in a certain time interval drop by drop.
Function throttling can be implemented in two main ways: timestamp and timer.
The time stamp
var throttle = function(func, delay) {var prev = Date.now();return function() {var context = this;var args = arguments;var now = Date.now();if(now - prev >= delay) { func.apply(context, args); prev =Date.now(); }}}function handle() {console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
Copy the code
The timer
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if(! timer) { timer =setTimeout(function() {
func.apply(context, args);
timer = null; }, delay); }}}function handle() {
console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));
Copy the code
Function stabilization: Combine several operations into one operation. The idea is to maintain a timer that fires after the delay, but if it fires again within the delay, the timer will be cancelled and reset. In this way, only the last operation can be triggered.
Function throttling: causes functions to fire only once in a given period of time. The principle is to trigger the function by judging whether a certain time has been reached.
Difference: Function throttling guarantees that a true event handler will be executed within a specified period of time, no matter how frequently the event is triggered, whereas function buffering only fires once after the last event. For example, in an infinite load scenario, we want the user to make Ajax requests every once in a while while the page is scrolling, rather than asking for data when the user stops scrolling. This scenario is suitable for throttling technology to achieve.
5. Deep copy and shallow copy;
Deep copy and shallow copy only apply to complex objects such as Objects and arrays. In simple terms, a shallow copy copies the properties of an object at only one level, while a deep copy recursively copies all levels.
A shallow copy
var obj = { a:1.arr: [2.3]};var shallowObj = shallowCopy(obj);
function shallowCopy(src) {
var dst = {};
for (var prop in src) {
if(src.hasOwnProperty(prop)) { dst[prop] = src[prop]; }}return dst;
}
Copy the code
Because shallow copying only copies the attributes of an object sequentially, not recursively, and JavaScript stores objects as addresses, shallow copying causes obj.arr and shallowobj.arr to point to the same memory address.
shallowObj.arr[1] = 5; obj.arr[1] // = 5 Copy the code
Deep copy is different. It not only copies each attribute of the original object one by one, but also copies the objects contained in each attribute of the original object recursively to the new object.
It is important to note that if the object is large and has many levels, deep copy can cause performance problems. When you encounter scenarios that require deep replication, consider alternatives. In actual application scenarios, shallow replication is more common.
6. Do a 10-second countdown;
<! DOCTYPEhtml>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<script type="text/javascript">
function daojishi()
{
var starttime=document.getElementById("id2").innerText;
if(starttime==0)
{
return ;
}
setTimeout("daojishi()".1000);
starttime--;
document.getElementById("id2").innerText=starttime;
}
</script>
<body>
<h5 id="id2">10</h5>
<button id="id1" onclick="daojishi()">Start the countdown</button>
</body>
</html>
Copy the code
7. Use and differences between setTimeout() and setInterval()
1. SetTimeout () method
This method is supported by all browsers. SetTimeout () is a method that belongs to the window method, but we omit the top-level object name window
Set a time, and when the time is up, a method is executed.
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<script>
var x = 0;
function countSecond()
{
x = x+1;
document.haorooms.haoroomsinput.value = x;
setTimeout("countSecond()".1000)}</script>
</head>
<html>
<body>
<form name="haorooms">
<input type="text" name="haoroomsinput" value="0" size=4 >
</form>
<script>
countSecond();
</script>
</body>
</html>
Copy the code
The setInterval() method calls a function or evaluates an expression at a specified period in milliseconds. The setInterval() method will keep calling the function until
ClearInterval () is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
function test(){
this.name = "setInternal";
this.waitMes = function(){
var that = this;
setInterval(function(){
alert(that.name);
},3000); }}var te = new test();
te.waitMes();
</script>
</html>
Copy the code
As can be seen from the above, the main differences between setTimeout and setInterval are as follows:
1) setTimeout is run only once, that is to say, the specified code will be triggered to run after the set time expires, and the specified code will be finished after the run. If the same is run again in the running code
The setTimeout command can be run in a loop. (to loop, the function itself calls setTimeout() again); Setinterval runs in a loop, that is, every
The specified code is triggered when the interval is set. This is a real timer.
2) SetInterval is simple to use, while setTimeout is more flexible. It can exit the cycle at any time and can be set to run at an unfixed time interval, such as 1 second for the first time, 2 seconds for the second time, and 3 seconds for the third time.