Detailed explanations of the seven front-end questions of DD every week-second issue

Detailed explanations of the seven front-end questions of DD every week-second issue

Series Introduction

You look forward to the world, I look forward to your nothing bug. Hello everyone! I'm Lin Dada!

Daida will share seven front-end questions with everyone every week. The name of the series is "DD 7.Questions Weekly".

The main form of the series is: 3 JavaScript+ 2 HTML+ 2 CSS, to help us all consolidate the front-end foundation together.

All topics will also be integrated into LinDaiDai/niubility-coding-js is issueswelcomed everyone to provide a better problem-solving ideas, thank you .

Topic

1. Design a method to extract all key-value pairs with value greater than 2 in the object and return the latest object

achieve:

var obj = { a: 1, b: 3, c: 4 }
foo(obj) //{ b: 3, c: 4 }
 

There are many ways to provide a more concise wording here, uses ES10the Object.fromEntries():

var obj = { a: 1, b: 3, c: 4 }
function foo (obj) {
  return Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => value > 2)
  )
}
var obj2 = foo(obj) //{ b: 3, c: 4 }
console.log(obj2)
 
//ES8  Object.entries() 
var obj = { a: 1, b: 2 }
var entries = Object.entries(obj); //[['a', 1], ['b', 2]]
//ES10  Object.fromEntries() 
Object.fromEntries(entries); //{ a: 1, b: 2 }
 

github.com/LinDaiDai/n...

2. Implement a padStart() or padEnd() polyfill

String.prototype.padStartAnd String.prototype.padEndare ES8in the new method allows an empty string or other string to the beginning or end of the original string. Let's first look at the usage syntax:

String.padStart(targetLength,[padString])
 

usage:

'x'.padStart(4, 'ab') //'abax'
'x'.padEnd(5, 'ab') //'xabab'

//1.  
'xxx'.padStart(2, 's') //'xxx'

//2.   " " 1 
//3.  
'xxx'.padStart(5, 'sss') //ssxxx

//4.  
'12'.padStart(10, 'YYYY-MM-DD') //"YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') //"YYYY-09-12"
 

polyfillachieve:

String.prototype.myPadStart = function (targetLen, padString = " ") {
  if (!targetLen) {
    throw new Error(' ');
  }
  let originStr = String(this); // ,  this String{} String 
  let originLen = originStr.length; // 
  if (originLen >= targetLen) return originStr; //    >    
  let diffNum = targetLen - originLen; //10 - 6// 
  for (let i = 0; i < diffNum; i++) { // 
    for (let j = 0; j < padString.length; j++) { // padString 1
      if (originStr.length === targetLen) break; // 
      originStr = `${padString[j]}${originStr}`;
    }
    if (originStr.length === targetLen) break;
  }
  return originStr;
}
console.log('xxx'.myPadStart(16))
console.log('xxx'.padStart(16))
 

It's still relatively simple, and padEndthe implementation is the same as it, just change the position forin the second layer of loop ${padString[j]}${orignStr}.

github.com/LinDaiDai/n...

3. use regular to write a method to get the value in the cookie according to the name

function getCookie(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)'));
  if (match) return unescape(match[2]);
}
 
  1. To get the cookie on the page, you can use document.cookie to get a string similar to this:
'username=lindaidai; user-id=12345; user-roles=home, me, setting'
 

You can see several messages:

  • Each cookie is of name=valuesuch a form of storage
  • The beginning of each item may be an empty string ''(for example username, the beginning is actually), or it may be an empty string ' '(for example user-id, the beginning is)
  • Each use ";"to distinguish
  • If there are a plurality of values in a particular time, with ","(for example to connect the user-rolesvalue)
  • At the end of each item may have ";"(such as usernamethe end), it may not (such as user-rolesthe end)
  1. So we split the regularity here:
  • '(^| )'It means to get the beginning of each item, because we know that if it ^is not placed []in it, it means that it matches at the beginning. So (^| )the meaning here is actually split into the case of the (^)indicated match username, nothing in front of it is an empty string (you can (^)understand ^it as there is a hidden behind it ''); and |it means or is a " "(for Matches user-idthe case at the beginning)
  • +name+There is nothing to say
  • =([^;]*)The matching here is the =latter value, for example lindaidai; just said that ^if it is placed []in it, it means " ^ "that it means not. So here it means that everything else ([^;]*)except ";"this string matches ( *you should know what it means, match 0 or more times)
  • Some big guys write this after the equal sign '=([^;]*)(;|$)', but why can it be '(;|$)'omitted in the end? Because there is actually no last cookieitem ';', it can be merged into =([^;]*)this step.
  1. The final result is matchactually an array of length 4. such as:
[
  "username=lindaidai;",
  "",
  "lindaidai",
  ";"
]
 
  • Item 0: Full amount
  • Item 1: Beginning
  • Item 2: Middle value
  • Item 3: End

So we are going to take match[2]the value of the second term .

  1. In order to prevent the obtained value from being %xxxsuch a sequence of characters, it is necessary to use a unescape()method to decode it.

github.com/LinDaiDai/n...

4. implement a drag and drop (compatible writing)

" Inspect knowledge points "

  1. eventCompatibility
  • Other browserswindow.event
  • There is no under Firefox window.event, so use the passed parameter evinstead
  • Final wording:var oEvent = ev || window.event
  1. What are the events that implement drag and drop ( boxfor elements that need to be dragged and dropped)
  • box.onmousedown
  • document.onmousemove
  • document.onmouseup
  1. Realized sequence of events
  • First monitor box.onmousedown, that is box, the event triggered when the mouse is pressed , and record the distance from the top and left of the screen when the mouse is pressed, and the boxdistance from the top and left of the screen, and then subtract the latter from the former to get the difference distanceXsumdistanceY
  • Then listen to the document.onmousemoveevent in this event , record the distance from the top and left of the screen each time the mouse moves, then use them to subtract the distanceXsum distanceY, and then assign it to boxthe leftsum topso that it can follow the mouse movement
  • But need to consider boxthe boundary conditions from the top/bottom/left/right of the screen
  • When document.onmouseupyou need to set the document.onmousemoveevent tonull

as the picture shows:

Coding

css

<style>
  html, body {
    margin: 0;
    height: 100%;
  }
  #box {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    top: 100px;
    left: 100px;
  }
</style>
 

html

<div id="box"></div>
 

javascript

window.onload = function () {
  var box = document.getElementById('box');
  box.onmousedown = function (ev) {
    var oEvent = ev || window.event; // , window.event
    var distanceX = oEvent.clientX - box.offsetLeft; //  - box 
    var distanceY = oEvent.clientY - box.offsetTop;
    document.onmousemove = function (ev) {
      var oEvent = ev || window.event;
      var left = oEvent.clientX - distanceX;
      var top = oEvent.clientY - distanceY;
      if (left <= 0) {
        left = 0;
      } else if (left >= document.documentElement.clientWidth - box.offsetWidth) {
        left = document.documentElement.clientWidth - box.offsetWidth;
      }
      if (top <= 0) {
        top = 0;
      } else if (top >= document.documentElement.clientHeight - box.offsetHeight) {
        top = document.documentElement.clientHeight - box.offsetHeight;
      }
      box.style.left = left + 'px';
      box.style.top = top + 'px';
    }
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
}
 

(Thanks to Turbo328 for pointing out that the use document.onmouseupeffect will be box.onmouseupbetter)

github.com/LinDaiDai/n...

5. how to prevent bubbling and default events (compatible writing)

Stop bubbling:

function stopBubble (e) { // 
  if (e && e.stopPropagation) {
    e.stopPropagation();
  } else {
    //  IE
    window.event.cancelBubble = true;
  }
}
function stopDefault (e) { // 
  if (e && e.preventDefault) {
    e.preventDefault();
  } else {
    //  IE
    window.event.returnValue = false;
    return false;
  }
}
 

github.com/LinDaiDai/n...

6. How to draw a fan shape? triangle?

/* */
.sector {
  width: 0;
  height: 0;
  border: 100px solid red;
  border-color: red transparent transparent transparent;
  border-radius: 50%;
}
/* */
.sector {
  width: 100px;
  height: 100px;
  border: 100px solid transparent;
  border-top-color: red;
  box-sizing: border-box; /*   */
  border-radius: 50%;
}
 
/* */
.triangle {
  width: 0;
  height: 0;
  border: 100px solid red;
  border-color: red transparent transparent transparent;
}
/* */
.triangle {
  width: 100px;
  height: 100px;
  border: 100px solid transparent;
  border-top-color: red;
  box-sizing: border-box;
}
 

github.com/LinDaiDai/n...

7. round? semicircle? oval?

div {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 20px;
}
.box1 { /*   */
  /* border-radius: 50%; */
  border-radius: 50px;
}
.box2 { /*   */
  height: 50px;
  border-radius: 50px 50px 0 0;
}
.box3 { /*   */
  height: 50px;
  border-radius: 50px/25px; /* x/y  */
}
 

github.com/LinDaiDai/n...

Afterword

You look forward to the world, I look forward to your nothing bug. This article will stop here.

You may spend 48hours at work every week , you will spend 49hours sleeping, and maybe you can spend more 20minutes on 7 dull questions. Over time, I believe we can all witness each other. Growth .

what? You ask me why the series is called DD? Because , haha .

Like " Lin blankly " guy also want to be concerned about the number of public Lin blankly LinDaiDaior sweep the following two-dimensional code .

I will update some front-end knowledge content and my own original articles from time to time

Your encouragement is the main motivation for my continuous creation .

This article uses mdnice typesetting