search
HomeWeb Front-endHTML TutorialCommon methods of native js organized

Common methods of native js organized

Nov 27, 2017 pm 03:21 PM
javascripttidymethod

With the rapid development of the front-end market, the current market requires talents to master more and more skills. Today I will summarize some native js closures, inheritance, prototype chain, and node. I hope it can help you on your front-end road. Helpful

The following is a personal summary, and some are copied by masters. Now they are put together for easy reference later (if there are any mistakes, I hope you can point them out and I will correct them as soon as possible).

1. !! Forced conversion to Boolean value boolean
Judge based on whether the value that needs to be judged is true or false. The true value returns true, and the prosthesis returns false. In this case, in addition to the false value, The rest is all true value.

False values ​​are: ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​null ​​undefined ​ ​ ​false​ ​NaN​ ​

Except these 6, the others are "true", including objects, arrays, Regularity, functions, etc.
Note: '0', 'null', 'false', {}, [] are also true values.
Then let’s take a look at how!! converts a Boolean value.
For example:
First we declare 3 variables, x is null, y is empty String, str is a string, let’s see what happens after they add "!!" result.

var x=null; var y=""; var str="abcd"; console.log(!!x) // false; console.log(!!y) // false; console. log(!!str) // true;

As mentioned above, false values ​​return false and true values ​​return true.

2. Add a ➕ sign in front of str. +str will force the conversion to Number
Add + in front of the string to force the conversion to number. Let’s try it together!

var str="88"; console.log(+str) // 88 //But if it is a mixed type string, it will be converted to NaN var b="1606e"; console.log( +b) // NaN

3. Unreliable undefined Reliable void 0
In JavaScript, assuming we want to determine whether an item is undefined, then we usually It would be written like this:

if(a === undefined){ dosomething..... }

Because in javascript, undefined is unreliable
For example:
When undefined is placed in the function function, we treat it as a local variable, which can be assigned a value. Let’s try it next.

function foo2(){ var undefined=1; console.log(undefined) } foo2(); // 1;

But when a global variable is defined within the function, It cannot be assigned a value

var undefined; function foo2(){ undefined=1; console.log(undefined) } foo2() // undefined

Then let’s try it void 0 or void (0) instead:
First declare a variable a and assign it to undefined. Next, we use void 0 to judge.

var a=undefined; //Use void 0 to judge if(a===void 0){ console.log('true') } // true //Use void (0) again Judge if(a===void (0)){ console.log('true') } // true //Finally we print the return values ​​of these two console.log(void 0,void (0)) // undefined undefined

We can now obtain undefined through void 0 operation; then when we need to judge that the value is undefined in the future, we can directly use void 0 or void (0), and these two The direct return value of value is undefined, so it is very reliable!

4. Strings also have length attributes!
We know that all Arrays have a length attribute. Even if it is an empty array, then the length is 0. Is there a string? Next let's verify it.

var str="sdfsd5565s6dfsd65sd6+d5fd5"; console.log(str.length) // 26

The result is there, so when we judge the type, we cannot simply take Is there a length attribute to determine whether it is an array? We can use the following method to determine whether it is an array:

var obj=[1,2]; console.log(toString.call(obj) == = '[object Array]');

5. How to create a random array, or scramble an existing array?
Sometimes we need a randomly scrambled array in the project, so let’s implement the following:
First create an array:

var arr=[]; for(var i= 0;i

Next let’s disrupt it:

arr.sort(()=>{ return Math.random() - 0.5 }) // [1, 0, 2, 3, 4 , 6, 8, 5, 7, 9]

The second method of shuffling:

arr.sort((a,b)=>{ return a>Math .random()*10; }) // [1, 2, 0, 6, 4, 3, 8, 9, 7, 5]

Our previous normal sorting was like this:

arr.sort(function(a,b){ return b-a });

Analysis:
Let’s talk about normal sorting first:
a,b represents any two elements in the array, if return > 0, b is before a and after a; if reutrn a-b output is sorted from small to large, b-a output is sorted from large to small.
Then let’s talk about how we disrupt it:
Needless to say, create an array. The next step is to use the js sort method to implement it. Math.random() implements a random decimal between 0-1 and then subtracts 0.5. , then it will be sorted according to the value obtained after return comparison, so it will generate a sorting that is not normal from large to small or small to large.

The second method of scrambling is also to follow the sort method, pass a and b in and then compare them with random numbers. The comparison method is not clear.

6. Remove all spaces before, after, before and after
This is a set of methods specially written for removing spaces. It is suitable for various situations, including all spaces, spaces before and after, spaces before and after.

var strr="    1 ad dertasdf sdfASDFDF DFG SDFG    "     //  type 1-所有空格,2-前后空格,3-前空格,4-后空格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"

Analysis:
This method uses a regular matching format. Later I will separate the regular rules to summarize a series, so stay tuned! ! !

\s: Space character, Tab, form feed character, newline character \S: All contents other than \s /g: Global match ^: Match at the beginning of the line $: Match at the end of the line + : Number of repetitions >0 * : Number of repetitions >=0 | : Or

replace(a,b): This method is used to replace some characters with other characters in the character creation, and will pass Enter two values ​​and replace the value a before the comma with the value b after the comma.

7. Letter case switching (regular matching, replace)
This method is mainly provided for some methods that require case conversion, mainly including the first letter in uppercase, the first letter in lowercase, uppercase and lowercase conversion, all Convert all to uppercase and all to lowercase.

type: 1: First letter capitalized 2: First letter lowercase 3: Case conversion 4: All uppercase 5: All lowercase

Original string:

var str="sdfwwerasfddffddeerAasdgFegqer"; function changeCase(str,type) {    //这个函数是第三个大小写转换的方法     function ToggleCase(str) {         var itemText = ""         str.split("").forEach(                 function (item) {                  // 判断循环字符串中每个字符是否以a-z之间开头的并且重复大于0次                     if (/^([a-z]+)/.test(item)) {                     //  如果是小写,转换成大写                         itemText += item.toUpperCase();                     }                 //  判断循环字符串中每个字符是否以A-Z之间开头的并且重复大于0次                     else if (/^([A-Z]+)/.test(item)) {                    //   如果是大写,转换成小写                         itemText += item.toLowerCase();                     }                     else{                   //  如果都不符合,返回其本身                         itemText += item;                     }                 });         return itemText;     }   //下面主要根据传入的type值来匹配各个场景     switch (type) {          //当匹配         case 1:             return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {                  //v=验证本身  v1=s ; v2=dfwwerasfddffddeerAasdgFegqer                 return v1.toUpperCase() + v2.toLowerCase();             });         case 2:             return str.replace(/^(\w)(\w+)/, function (v, v1, v2) {                 //v=验证本身  v1=s ; v2=dfwwerasfddffddeerAasdgFegqer                 return 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

Analysis:

split: used to split a string into a string array\w: numbers 0-9 or letters a-z and A-Z, or underscore\W: not \w, except the above Special symbols, etc. toUpperCase: Convert to uppercase toLowerCase: Convert to lowercase replace The second parameter can be a function. In the parameters of the function, the first one is itself, the second one is the regular matching content, and the third one matches the remaining The following content

Let’s verify it through a small experiment:
It is said on the Internet that replace can have 4 parameters, but I have not verified the meaning of the fourth representative. The first three parameters have been verified. The first parameter is the verification itself, the second parameter is the regular matching result, and the third parameter is the remaining value after the second match.

8. Loop the incoming string n times
str is a random string passed in, and count is the number of loops

var str="abc";  var number=555; function repeatStr(str, count) {     //声明一个空字符串,用来保存生成后的新字符串     var text = &#39;&#39;;     //循环传入的count值,即循环的次数     for (var i = 0; i < count; i++) {        //循环一次就把字符串+到我们事先准备好的空字符串上         text += str;     }     return text; }   console.log(repeatStr(str, 3))         // "abcabcabc"   console.log(repeatStr(number, 3))      // "555555555"

Analysis: According to the number of count loops, in the loop body Copy, return returns the value after +=

9. Replace the A content of the search string with the B content

let str="abacdasdfsd" function replaceAll(str,AFindText,ARepText){ raRegExp = new RegExp(AFindText,"g"); return str.replace(raRegExp,ARepText); } console.log(replaceAll(str,"a","x")) // xbxcdxsdfsd
str: ​​needs to be edited The string itself AFindText: the content that needs to be replaced ARepText: the content that is replaced
Analysis: create regular rules, match the content, replace

10. Detect common formats, email, mobile phone number, name, Uppercase, lowercase, when form verification, we often need to verify some content, here are some common verification examples.

function checkType (str, type) {     switch (type) {         case &#39;email&#39;:             return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);         case &#39;phone&#39;:             return /^1[3|4|5|7|8][0-9]{9}$/.test(str);         case &#39;tel&#39;:             return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);         case &#39;number&#39;:             return /^[0-9]$/.test(str);         case &#39;english&#39;:             return /^[a-zA-Z]+$/.test(str);         case &#39;chinese&#39;:             return /^[\u4E00-\u9FA5]+$/.test(str);         case &#39;lower&#39;:             return /^[a-z]+$/.test(str);         case &#39;upper&#39;:             return /^[A-Z]+$/.test(str);         default :             return true;     } } console.log(checkType (&#39;hjkhjhT&#39;,&#39;lower&#39;))   //false

Analysis:

checkType ('hjkhjhT','lower')'String to be verified','Matching format' email: Verification email phone: Verification mobile phone number tel: Verification Landline number number: Verify numbers english: Verify English letters chinese: Verify Chinese characters lower: Verify lowercase upper: Verify uppercase

I believe you have mastered the method after reading these cases, more exciting Please pay attention to other related articles on php Chinese website!


Related reading:

How to convert CSS encoding

css3 Click to display Ripple special effects

How to use canvas to realize the interaction between the ball and the mouse

The above is the detailed content of Common methods of native js organized. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use