search
HomeWeb Front-endHTML TutorialCommon methods of native js organized
Common methods of native js organizedNov 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft