Preface:
With the development of the front-end market with each passing day, today’s market is not only to cut the map of the small boy, little sister, but need to really understand the native JS closure, inheritance, prototype chain, Node, and read the source code of the big god, so we can not be too backward, roll up your sleeves, pick up the native JS bar! The following is a personal summary, there are also some copy god, now put together, convenient later access (there are wrong places, but also hope we can put forward, I will be corrected as soon as possible).
A,!!!!! Force a Boolean valueboolean
Depending on whether the current value is true or false, the true value returns true, and the false value returns false, so that all but false values are true.
False values are: 0, "", null, undefined,false, NaN,Copy the code
All but these six are true, including objects, arrays, re’s, functions, and so on. Note: ‘0’, ‘null’, ‘false’, {}, [] are also true values. So let’s see!! How to convert booleans. For example: first we declare three variables,x is null,y is an empty string, and STR is a string. Let’s see if they add “!!” And then what happens.
var x=null;
var y="";
var str="abcd"; console.log(!! x) //false; console.log(!! y) //false; console.log(!! str) //true;
Copy the code
As mentioned above, false values return false and true values return true.
2. Numeric stringstr
Forced to turnNumber
For numeric strings, such as “22” and “6”, you can directly convert them by using the following method: NULL can participate in the calculation, and null will be converted to 0 before the calculation.
- Prefixes the string
+
, you can force the transfernumber
, let’s try it together!
var str="88"; Console. log(+ STR) // 88 // But if it is a string of mixed types, it will be converted to NaN +"1606e"; // NaN + null ; / / 0Copy the code
- Subtract a number from a string
"11"- 1; // 10 null - 1 ; / / 1Copy the code
- Multiply the string by a number
"111" * 1 ; // 111
null * 1 ; // 0
Copy the code
- Divide a string by a number
"111" / 1 ; // 111
null / 1 ; // 0
Copy the code
Can also be used to judge:
if(toString.call(str*1)==[object Number]){
dosomething..
}
Copy the code
Unreliableundefined
reliablevoid 0
In JavaScript, if we want to determine if a variable is undefined, we usually write:
if(a === undefined){
dosomething.....
}
Copy the code
But in javascript, undefined is unreliable. For example, when undefined is placed inside function, we treat it as a local variable that can be assigned a value. Let’s try it out.
function foo2(){ var undefined=1; console.log(undefined) } foo2(); / / 1.Copy the code
But when you define a global variable inside a function, you can’t assign a value to it
var undefined;
function foo2(){
undefined=1;
console.log(undefined)
}
foo2() // undefined
Copy the code
Void (0) void (0) void (0) void (0) void (0) void (0)
var a=undefined; // use void 0 to checkif(a===void 0){
console.log('true'} / /true// Use void (0)if(a===void (0)){
console.log('true'} / /trueConsole. log(void 0,void (0)) // undefined undefinedCopy the code
We can now get undefined by void 0; Void (0) void (0) void (0) void (0) void (0) void (0)
4. Strings are also availablelength
Properties of!
We know that all arrays have a length property, even if it’s an empty Array, so length is 0, what about strings? So let’s verify that.
var str="sdfsd5565s6dfsd65sd6+d5fd5";
console.log(str.length) // 26
Copy the code
We can use the following method to determine whether the type is an array:
Var obj = [1, 2]; console.log(toString.call(obj) ==='[object Array]');
Copy the code
5, how to create a random number group, or the existing array shuffled?
Sometimes in a project we need a randomly scrambled array, so let’s implement the following:
var arr=[];
for(var i=0; i<10; i++){ arr.push(i) } console.log(arr) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Copy the code
Let’s mess it up:
arr.sort(()=>{
returnMath. The random () to 0.5}) / / [1, 0, 2, 3, 4, 6, 8, 5, 7, 9]Copy the code
The second method of disruption:
arr.sort((a,b)=>{
return a>Math.random()*10;
}) // [1, 2, 0, 6, 4, 3, 8, 9, 7, 5]
Copy the code
Our normal order used to look like this:
arr.sort(function(a,b){
return b-a
});
Copy the code
Resolution:
Return (a,b); return (a,b); If reutrn < 0, a comes before B comes after; When a=b, there is browser compatibility; A-b outputs are sorted from smallest to largest, and B-A outputs are sorted from largest to smallest. And then the way we do it: Math.random() implements a random decimal number between 0 and 1 and subtracts 0.5. This sort will be based on the result of the return comparison, so it will not be the normal sort from large to small or from small to large.
The second scrambling method is to follow the same sort method, pass in a and B and compare with random numbers. The method of comparison is not clear.
Remove all blanks before, after and before
This is a set of methods written specifically for removing whitespace, all whitespace, before and after whitespace, before and after whitespace.
var strr=" 1 ad dertasdf sdfASDFDF DFG SDFG "
// type1- all Spaces, 2- front and back Spaces, 3- front Spaces, 4- back SpacesCopy the code
function trim(str,type){
switch (type) {case 1:return str.replace(/\s+/g,"");
case 2:return str.replace(/(^\s*)|(\s*$)/g, "");
case 3:return str.replace(/(^\s*)/g, "");
case 4:return str.replace(/(\s*$)/g, "");
default:return str;
}
}
console.log( trim(strr,1)) // "1addertasdfsdfASDFDFDFGSDFG"
Copy the code
Resolution:
\ s: Spaces, tabs, and change pages, newline \ s: not all \ s/g: global match ^ : match at the beginning of $: matching line tail + : repeat number > 0 * : repeat number > = 0 | : orCopy the code
Replace (a,b) : The replace(a,b) method is used to replace some characters with other characters in a character creation, passing in two values that replace the value a before the comma with the value B after the comma.
If you only want to remove the front and rear whitespace, you can use js trim() method directly:
let str = " abcd ";
str.trim() // "abcd"
Copy the code
I have an article devoted to regular matching.portal
7, letter case switching (regular matching,replace
)
This method is mainly used for some methods that need to be converted to uppercase, lowercase, lowercase, all uppercase and all lowercase.
type: & emsp;   1: uppercase     2: home parent lowercase     3: Case conversion & EMsp;   4: all caps     5: all lowercase    Copy the code
Original string:
var str="sdfwwerasfddffddeerAasdgFegqer";
function changeCase(str,type) {// This function is the third case conversion methodfunction ToggleCase(str) {
var itemText = ""
str.split("").forEach(
function(item) {// Determines whether each character in the loop starts with a and z and is repeated more than 0 timesif(/ ^ ([a-z] +) /. The test (item)) {/ / if it is lowercase, converted to uppercase itemText + = item. The toUpperCase (); } // Determine if each character in the loop starts between A and Z and is repeated more than 0 timeselse if(/ ^ ([a-z] +) /. The test (item)) {/ / if it is A capital, converted to lowercase itemText + = item. ToLowerCase (); }elseItemText += item; }});returnitemText; } // The following is mainly based on the incomingtypeValue to match each scenario switch (type) {// When matchedcase 1:
return str.replace(/^(\w)(\w+)/, function(v, v1, v2) {// v1=s; v2=dfwwerasfddffddeerAasdgFegqerreturn v1.toUpperCase() + v2.toLowerCase();
});
case 2:
return str.replace(/^(\w)(\w+)/, function(v, v1, v2) {// v1=s; v2=dfwwerasfddffddeerAasdgFegqerreturn v1.toLowerCase() + v2.toUpperCase();
});
case 3:
return ToggleCase(str);
case 4:
return str.toUpperCase();
case 5:
return str.toLowerCase();
default:
return str;
}
}
console.log(changeCase(str,1)) //SdfwwerasfddffddeerAasdgFegqer
Copy the code
Resolution:
Split: Used to split a string into an array of strings \w: numbers 0-9 or letters A-z and a-z, or underscores \w: The second argument can be a function in which the first argument is itself, the second argument matches the content of the re, and the third argument matches the rest of the contentCopy the code
Replace the second argument can be a function. The first argument of the function is itself, the second argument matches the content of the re, and the third argument matches the rest of the content.
SessionStorage store object
// Object to store:let obj={
hellow:world
};
letstr=JSON.Stringify(obj); -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / is simple to use: deposit: sessionStorage. SetItem ("Param",str); Pick up:let get_data=JSON.parse(sessionStorage.getItem("Param")). Hellow / / world -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / further consolidation: deposit: sessionStorage. SetItem ("Param",JSON.stringify({Hellow:world})); Take: JSON. Parse (sessionStorage. The getItem ("Param")).Hellow // world
Copy the code
Ix. Console prints execution time
Sometimes we need to compare the execution efficiency of two methods, or check the execution time of a method, so we can use the following method as a listening method.
console.time("Start time:") // Put the method you want to execute in the middle of it console.timeEnd("End time:")
Copy the code
reference
X. Explore the double equal sign “==” and the identity “===”
The == and === operators are used to compare whether two values are equal, although they have different definitions of equality. The two operators allow operands of any type, returning true if the operands are equal, false otherwise. So what’s the difference between == and ===? Let’s explore.
Reference: The Definitive Guide
‘= = =’ identity
The === strict equality operator evaluates the value of its operand and then compares the two values without any type conversion:
- If two types are not the same, they are not equal.
For example, '1 ==='true' // false`
Copy the code
- If both values are
null
Or areundefined
, then they are equal.
For example, null === undefined //false
null === null // true
undefined === undefined // true
Copy the code
- If both values are Boolean
true
Or arefalse
, then they are equal.
Such as:true= = =true // true
Copy the code
- If one of the values is zero
NaN
, or bothNaN
, then they are not equal. (NaN
Is not equal to any other value, including itself. throughx! ==x
To see if x isNaN
Only if thex
forNaN
When, the value of this expression is zerotrue
)
For example, NaN === NaN //falseNaN ! == NaN //true
Copy the code
- If two reference values refer to the same object, array, or function, they are equal. If they point to different objects, they are not equal, even though the two objects have exactly the same properties.
For example, var obj = {}; obj === obj ; //truevar obj1 = {a:1}; var obj2 = {a:1}; Obj1 = = = obj2; //false
Copy the code
- If two value types are equal and the values are not equal, then they are not equal.
Such as:true= = =false; // false
"1"= = ="8" // false.Copy the code
- If two values are equal and their types are equal, then they are equal.
Such as:"1"= = ="1"; // true8 = = = 8; //true
"true"= = ="true"; // true
false= = =false;
undefined === undefined; // true
null === null; // true.Copy the code
‘= =’ equal
The equality operator “==” is similar to the identity operator, but the equality operator is not strictly compared. If the two operands are not of the same type, the equality operator tries to do some type conversion and then compares them.
- If two values are of the same type but have different values, they are not equal.
Such as:"1"= ="3"; // false
"true"= ="false"; // false
false= =true // false.Copy the code
- If one value is null and one value is undefined, they are equal.
For example, null == undefined //true
Copy the code
- If one of them is a Boolean value, it is converted to a number, true to 1, false to 0, and then the comparison is advanced.
Example: 1 ==true; // true
false= = 0 / /true
true= =false // false
Copy the code
- If one of them is a number and the other is a string, the string is converted to a number and then the converted value is used for comparison.
Example: 1 =="1" // true
"500"/ / = = 800false
Copy the code
- If one value is an object and the other is a number or string, the object needs to be converted to its original value (through toString() or valueOf().js built-in classes first try valueOf() and then toString(), except for date classes, which only use toString()). And then compare.
var obj ={a:"b"};
obj.toString(); // "[object Object]"
1 == obj; // false
Copy the code
- If two objects are of the same type but have different reference addresses, they are not equal.
For example: [] == [] //false{} = = {} / /false
Copy the code
Here’s an interesting interview question:
For example: [] ==! [] / /trueWhy is thistrue? Because of "!" The priority of "==" is greater than "==", so calculate the right side first,! [] for resultsfalseAnd [] = =! [] is equivalent to => [] ==false; If one value is an object and the other is a number or string, convert the object to its original value and compare: [].toString() =>' '[] = =falseEquivalent = >""= =falseConvert to a number:""= =falseEquivalent to => 0 == 0 In this case, the type is the same. The comparison value is 0 == 0 //trueThe values are equal, so the result is zerotrue
Copy the code
A few points to note:
1. Type judgment is performed first, and values of the same type are directly compared
2. Note that undefined is equal to null
3. Determine the type of the value, such as non-object, convert all the value into number, and then compare the ratio.
Note: all false values are converted to0
, true to1
Encode and decode strings as URI components
encodeURIComponent()
Function encodes a string as a URI component.
encodeURIComponent("Chinese") / /"%E4%B8%AD%E6%96%87"
Copy the code
decodeURIComponent()
The function can beencodeURIComponent
The encoded data is encoded
decodeURIComponent("%E4%B8%AD%E6%96%87") / /"Chinese"
Copy the code
Uuid generates a random string (higher than random)
Usually, when we use random numbers, we may think of the following:
⇨ 0.3920174387754096 Math. The random ()Copy the code
Today’s recommendation is for a high-order method for generating random strings: UUID
UUID, short for Universally Unique Identifier, is a standard for software construction and is part of the Open Software Foundation’s effort in distributed computing environments to ensure that all elements of a distributed system have Unique identifying information. There is no need to specify identification information through the central control terminal. This way, each person can create a UUID that doesn’t conflict with anyone else. In this case, there is no need to worry about name duplication at database creation.
A UUID is a set of 32-bit hexadecimal numbers, so the theoretical total number of UUID’s is 16^32=2^128, which is approximately 3.4 x 10^38. So if you generate 1 trillion UUID per nanosecond, it would take 10 billion years to use up all of them.
The standard form of UUID consists of 32 hexadecimal digits, hyphenated into five paragraphs of the form 8-4-4-12.
Example:
550e8400-e29b-41d4-a716-44665544 0000Copy the code
NPM address of the UUID
Online introduction:
Version 4 is recommended:
<script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script>
<script>
uuidv4(); // ⇨ v4 UUID
</script>
Copy the code
Version 5 is recommended:
<script src="http://wzrd.in/standalone/uuid%2Fv5@latest"></script>
<script>
uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ v5 UUID
</script>
Copy the code
NPM download:
npm install uuid
Copy the code
Import on demand according to version number:
<! -- version 4--> const uuidv4 = require('uuid/v4'); uuidv4(); / / ⇨'10ba038e-48da-487b-96e8-8d3b99b6d18a'
Copy the code
Clipboard. js: Copy text function
Today I recommend another feature to use, which is our copy, independent of Flash, independent of other frameworks, gzip compressed only 3KB in size
ClipboardJS official website address
1. Copy
Copy: A very common use case is to copy content from another element. You can do this by adding a data-clipboard-target attribute to the target element. The value of this attribute is a selector that matches another element.
- The third party
CDN
Introduction method:address
Here is a simplified version of the native HTML scene
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
</head>
<body>
<script>
new ClipboardJS('.btn');
</script>
<input id="foo" value=I'm Content 5555 style='width:300px'>
<button class="btn" data-clipboard-target="#foo"</button> </body> </ HTML >Copy the code
npm
Download method:
npm install clipboard --save
Copy the code
Here is how to use the React component:
import React, { useEffect } from 'react';
import ClipboardJS from 'clipboard'
const App = () => {
useEffect(() => {
const clipboard = new ClipboardJS('.btn'// The clipboard is destroyed when the component is destroyedreturn () => clipboard.destroy()
}, [])
return (
<>
<input id="copy-text" value={'content'} />
<button className="btn" data-clipboard-target="#copy-text"</button> </>)}export default App;
Copy the code
2. Shear
Clipping: You can define a data-clipboard-action=’cut’ property to indicate whether you want to copy or cut the content as follows:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
</head>
<body>
<script>
new ClipboardJS('.btn');
</script>
<input id="foo" value=I'm Content 5555 style='width:300px'>
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#foo"</button> </body> </ HTML >Copy the code
3. Copy the text from the property
To copy text from an attribute, simply say that you don’t have to copy text from another element. You just set a data-clipboard-text attribute to the target element
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
</head>
<body>
<script>
new ClipboardJS('.btn'); </script> // Here click the button, the contents of the paste board is data-clipboard-text value <button class="btn" data-clipboard-text="Here's what I want."</button> </body> </ HTML >Copy the code
4. Callback after copy/cut:success / error
Sometimes we need to give the user some feedback after copying/cutting. Here we use the event callback as follows
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
</head>
<body>
<script>
var clipboard = new ClipboardJS('.btn'); // Successful callback clipboard.on('success'.function(e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger); e.clearSelection(); }); // Failed callback clipboard.on('error'.function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
</script>
<button class="btn" data-clipboard-text="Here's what I want."</button> </body> </ HTML >Copy the code
(Above part, there is a reference waiting! Daishen’s article github.com/chenhuiYj/e…)
If you are interested in my article or have some suggestions for me to listen to 👂, you can also add wechat oh!
If the pro feel my article is good, you can add attention to oh!
Finally, I wish you all the best! - Rookie ChristineCopy the code