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 issues
welcomed 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 ES10
the 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 }
2. Implement a padStart() or padEnd() polyfill
String.prototype.padStart
And String.prototype.padEnd
are ES8
in 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"
polyfill
achieve:
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 padEnd
the implementation is the same as it, just change the position for
in the second layer of loop ${padString[j]}${orignStr}
.
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]);
}
- 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=value
such a form of storage - The beginning of each item may be an empty string
''
(for exampleusername
, the beginning is actually), or it may be an empty string' '
(for exampleuser-id
, the beginning is) - Each use
";"
to distinguish - If there are a plurality of values in a particular time, with
","
(for example to connect theuser-roles
value) - At the end of each item may have
";"
(such asusername
the end), it may not (such asuser-roles
the end)
- 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 matchusername
, 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 Matchesuser-id
the case at the beginning)+name+
There is nothing to say=([^;]*)
The matching here is the=
latter value, for examplelindaidai
; 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 lastcookie
item';'
, it can be merged into=([^;]*)
this step.
- The final result is
match
actually 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 .
- In order to prevent the obtained value from being
%xxx
such a sequence of characters, it is necessary to use aunescape()
method to decode it.
4. implement a drag and drop (compatible writing)
" Inspect knowledge points "
event
Compatibility
- Other browsers
window.event
- There is no under Firefox
window.event
, so use the passed parameterev
instead - Final wording:
var oEvent = ev || window.event
- What are the events that implement drag and drop (
box
for elements that need to be dragged and dropped)
box.onmousedown
document.onmousemove
document.onmouseup
- Realized sequence of events
- First monitor
box.onmousedown
, that isbox
, 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 thebox
distance from the top and left of the screen, and then subtract the latter from the former to get the differencedistanceX
sumdistanceY
- Then listen to the
document.onmousemove
event in this event , record the distance from the top and left of the screen each time the mouse moves, then use them to subtract thedistanceX
sumdistanceY
, and then assign it tobox
theleft
sumtop
so that it can follow the mouse movement - But need to consider
box
the boundary conditions from the top/bottom/left/right of the screen - When
document.onmouseup
you need to set thedocument.onmousemove
event 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.onmouseup
effect will be box.onmouseup
better)
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;
}
}
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;
}
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 */
}
Afterword
You look forward to the world, I look forward to your nothing bug
. This article will stop here.
You may spend 48
hours at work every week , you will spend 49
hours sleeping, and maybe you can spend more 20
minutes 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 LinDaiDai
or 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