Common methods of native js organized
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"
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 = ''; //循环传入的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 'email': return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'phone': return /^1[3|4|5|7|8][0-9]{9}$/.test(str); case 'tel': return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case 'number': return /^[0-9]$/.test(str); case 'english': return /^[a-zA-Z]+$/.test(str); case 'chinese': return /^[\u4E00-\u9FA5]+$/.test(str); case 'lower': return /^[a-z]+$/.test(str); case 'upper': return /^[A-Z]+$/.test(str); default : return true; } } console.log(checkType ('hjkhjhT','lower')) //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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement
