Common methods of native js organized

php中世界最好的语言
Release: 2017-11-27 15:21:16
Original
2274 people have browsed it

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<10;i++){ arr.push(i) } console.log(arr) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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 < 0, a is before b and after ; When a=b, there is browser compatibility;
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"
Copy after login

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
Copy after login

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"
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template