30 sections of Useful JavaScript code

Source: Internet
Author: User
Tags set time

1. How to differentiate between IE and non-IE browser

If(!+[1,]) { Console.log ("This is IE browser"else{ console.log ("This is not IE browser"); }
<script type= "Text/javascript" >alert ([]);//equivalent to alert ([1,2].tostring ());--this is the same on IE and non-ie, will pop up "alert ([1,]);//equivalent to alert ([1,].tostring ());--in non-IE standard browser, JS engine will automatically delete the last ",", so on IE will pop up "1," and on non-ie will pop up "1"Alert (+[1,]);//According to the above explanation, this sentence on IE equivalent to alert (+ "1,"), and on non-ie equivalent to alert (+ "1"), the role of positive sign is to try to convert the string to a number, "1," of course, is not a number, and "1" can be converted to the number 1, So the final result: IE will fail to pop "NaN", instead of the number "1" will pop up on IE browser //the above + number conversion string is a test of the numbervars = + "5"; alert (S+1); //OK, so far, we know +[1,] end up in IE Nan, the number 1 on non-IE browsers //Let's take a look at the very personality of NanAlert (nan==true);//Eject FalseAlert (nan==false);//Eject Falsealert (Nan==nan);//Eject False //that is, Nan is false regardless of who compares it .Alert (! NaN);//equivalent to alert (! ( Nan==true)), according to the above explanation of course is popup true  //So, alert (!+[1,]) will eventually pop up on ie "true", and then look at Firefox and other non-IE browser performanceAlertNewBoolean (0));//falseAlertNewBoolean (1));//trueAlertNewBoolean (-1));//true//that is: The number 0 will be converted to false, and any other number will be converted to true, so ultimately on non-IE browser is ultimately equivalent to:Alert (!1);//thatAlert (!true)//will eventually get false //in summary: The following judgment will be able to determine whether the browser is IEif(!+[1,]) {Alert ("I am the real IE browser!")}Else{alert ("I'm not ie!.")}</script>
This operation in IE6, 7, 8 is right, but in 9, 10, 11 has been fixed, and other modern browser display effect is the same, so, this use to make a distinction!
2. Convert the date directly to a value
+new Date ();
3. Non-IE browser will be the class array object ' arguments ' dedicated to arrays

Array.ptrototype.slice.call (arguments);

Arguments is not an instance of array, so it is not a real array, there is no slice () method, but why use "Array.prototype.slice" instead of "array (). Slice" or "[].slice ()"? Because the two methods are inefficient, use the notation in the code to access the built-in functions of the array.
4. The simplest operator

var a = 0 | | 3; Console.log (a); // Results 3

If the first value after = evaluates to a Boolean value of True, the value of a is taken 1th, otherwise the 2nd is taken.
5. Single-Chain calculation

var a = ten; Console.log (a+ 1);

"A-1" is executed first, "a = A+1" is performed.
6. Interesting void operator <a href= "javascript:void (0)" > I'm a dead link </a>

Void is an operator used to evaluate an expression but not return a value. Usage: javascript:void (expression), expression is a standard JavaScript expression to be computed.
7  . Jump to a new page and ensure that the browser does not return location.replace ("url");

The replace () method of location can replace the current document with a new document, and the method overwrites the records in the History object.
8. After a few seconds return to previous page <meta htt-equiv= "Refresh" content= "3, Url=javascript:window.hostory.go (-1);" >

Where content is the set time
9  refreshes the parent window window.opener.location.reload () In the Open child window ;
10. Verify that the regular expression /^-\d+$/.test (str) is negative;

 One  . Print Web page window.print () with JavaScript; Window.print () is a browser built-in API that can print pages directly
12. Show/Hide a DOM element El.style.display = ""= "None";  The display/hide of DOM elements is  implemented primarily by setting the style of the element display property. 
 - Implement the Text wrap alert ("P\NP") in Alert ().  "\ n" represents the line break. 
14. Implement ECMASCRIPT5 in Object.create () function   Clone (proto) {     function  _ Clone () {}     =proto;      = _clone;      return new _clone;                    //  }    var me = clone (person);  Inherited as a prototype chain, the constructor re-points to the newly created object. 
15. Understanding Closures in JavaScript//For example, the following code will output 5 times, the result is 5, how to Output 1, 2, 3, 4?  for(vari=0; i<5;i++) {setTimeout (function() {console.log (i); },1000);} //5 times the results are all 5 .
//Using the closure principle to implement the code as follows for(vari=0; i<5;i++) { (function(e) {setTimeout (function() {Console.log (e); },1000); }) (i)}//5 times the results are 0,1,2,3,4.
16. Detect SHIFT, ALT, CTRL // The following is the browser built-in detection method Event.shiftkey;         // detect shiftEvent.altkey;         // detect AltEvent.ctrlkey;         // Detect CTRL
 -  get wide, high window.screen.height of screen resolution ;    // Get screen height window.screen.width;    // Get screen width Window.screen This object contains information about the user's screen
 - . How the script never goes wrong function (M, F, l) {   returntrue;};
 19   console.log ( "a". charCodeAt (0)); //  97  Console.log (String.fromCharCode (75)); // k  charcodeat () returns the Unicode encoding of the specified position character, fromCharCode () takes a specified Unicode value, and returns a string. 
 20 var  demo = {name: "Ki" Span style= "color: #000000;"         >}demo.name;       // ki  demo[' name ']; // ki  //  var  get = ' name ' ;d Emo[get];  // ki  
21. The simplest way to convert a value to a Boolean value!! " Demo "      //true!!" ;              false!! ' 0 ';            true!! ' 1 ';            true!! {};            true!! true;         True use  "! "Operator two times, you can convert a value to a Boolean value
22. Determine if the browser supports HTML5!! navigator.geolocation; in HTML5, Navigator.geolocation can obtain the current location of the device by  "!" It is possible to determine whether the API is supported, that is, whether HTML5 is supported. 
23. Decide whether to support canvasfunction  iscanvas ()    {return !! Document.createelement (' canvas '). GetContext;  }
 -  . Determine the IE version window.navgator.appVersion the above code returns a string that represents the version number of the browser being used. He may contain only one number, such as 5.  0, it may also contain some additional information. 
25. Declaring variable abbreviations and complex notation/ * complex notation */var  x; var y; var z=3; /* abbreviated wording */ var x, y, z=3;  JavaScript is a more flexible language, and it can be programmed with the best possible use of abbreviations, which improves JavaScript performance. 
26. Use lazy loading scheme to improve function code performancefunctionaddevents (type, element, fun) {if(Element.addeventlistener) {Element.addeventlistener (type, fun,false); }Else if(element.attachevent) {element.attachevent (' On ' +type, fun); }    Else{element[' on ' +tyoe] =Fun ; }   }//The so-called lazy loading is the first execution of the code, using the internal method of the function code to overwrite the original code, the code is as follows:varAddevents = (function() {     if(Element.addeventlistener) {Element.addeventlistener (type, fun,false); }Else if(element.attachevent) {element.attachevent (' On ' +type, fun); }    Else{element[' on ' +tyoe] =Fun ; }   })();
27. Capture the Ctrl+enter key if(event.ctrlkey && Event,keycode = =) {    Console.log ("You Pressed the Ctrl+enter ")}= = 13 detects the Enter key. 
 -  . Gets the number of browser plugins navigator.plugins.length; use Navigator to detect browser versions, supported MIME types, installed plug-ins (plugin). 
29. Implement operation on Windows, MAC, Unix operating systemvarOsType = "", Windows= (Navigator.userAgent.indexOf ("Windows", 0)!=-1)? 1:0, Mac= (Navigator.userAgent.toLowerCase (). IndexOf ("Mac", 0)!=-1)? 1:0, Linux= (Navigator.userAgent.indexOf ("Linux", 0)!=-1)? 1:0, Unix= (Navigator.userAgent.indexOf ("X11", 0)!=-1)? 1:0; if(Windows) OsType = "Windows"; Else if(MAC) OsType = "Mac"; Else if(Linux) OsType = "Linux"; Else if(Unix) OsType = "Unix"; Console.log (OsType); Navigator.useragent represents a user agent. 
30. Use native JavaScript to determine if it is a mobile device browser var mobilereg =/iphone|ipod|android.*mobile|windows.*phone| blackberry.*mobile/if(Mobilereg.test (Window.navigator.userAgent.toLowerCase ())) {    Alert ("mobile device! ");}Else  {    alert (" non-mobile device! ");}

30 sections of Useful JavaScript code

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.