"summarize" JavaScript Learning summary-tips, methods, Details

Source: Internet
Author: User
Tags time in milliseconds

Variable conversions
var myVar  = "3.14159", str   = "" "+ myVar,//  String type int   / /number  type float  // number type bool  // Boolean type array  //  Array type

however, the conversion date (new date (myVar)) and the regular expression (new RegExp (myVar)) must use the constructor, and a simplified form such as/pattern/flags is used when creating the regular Expression.

Rounding and converting to numerical type
//when a character variable participates in an operation, JS automatically converts it to a numeric type (if it cannot be converted, it becomes Nan)' 10.567890 ' | 0//Ten//all numerical types in JS are double-precision floating-point numbers.//As a result, JS will first convert these numeric operands to integers when performing bit operations, and then perform the operations//| is binary or, x|0 is always equal to x;//^ for xor, same as 0 xor 1, so x^0 is always equal to x;//~ is a bitwise reverse, two times after the value of course is the same' 10.567890 ' ^ 0//Results: Ten-2.23456789 | 0//-2~~2.23456789//2~~-2.23456789//-2~-2.23456789//1~2.23456789//-3
Date to Value
// the internal representation of the time of JS itself is the UNIX timestamp, which records the current unit     of time in milliseconds from 0 o'clock January 1, 1970. var d = +new//1488947616099
Class Array object to array
var arr =[].slice.call (arguments)

The following example:

function test () {  var res = [' a ', ' B '];   // Method 1  res = Res.concat ([].slice.call (arguments,0));  // 0 can be omitted to indicate interception    from the start position // Method 2   Array.prototype.push.apply (res, arguments);} Test (' C ', ' d ');  // ["a", "b", "c", "d"]
Conversion between the binaries
(int//  converts int to hex, eg + = "C"(int//  converts int to octal, eg. "+"//  converts hex to int, eg. "FF" = 255//  converts octal to int, eg. "+"
Determine if it is IE
//Edit Http://www.lai18.com//seemingly the shortest, using IE does not support the standard ECMAScript of the array in the end of the comma-ignored mechanismvarIE =!-[1,];//using the conditional annotations of IEvarie =/*@[email protected]*/false;//or conditional commentvarIe//@cc_on =1;//IE does not support vertical tabsvarie = ' \v ' = = ' V ';//Principle Ibid .varIE =!+ "\v1";
Try to use native methods

To find the largest number in a set of numbers, we might write a loop, for example:

var numbers = [3,342,23,22,124]; var max = 0;  for (var i=0;i<numbers.length;i++if(numbers[i] > max) {  =  numbers[i]; }}alert (max);

In fact, using the native method, can be more simple to achieve

var numbers = [3,342,23,22,124];numbers.sort (function(b) {return b- a}); Alert (numbers[0]);

of course, the simplest way is:

// returns 433

You can also do this now:

// Take maximum value // take the minimum value
Event delegation

A simple example: the HTML code is as Follows:

<H2>Great Web Resources</H2><ulID= "resources"> <Li><ahref= "http://opera.com/wsc">Opera WEB Standards Curriculum</a></Li> <Li><ahref= "http://sitepoint.com">SitePoint</a></Li> <Li><ahref= "http://alistapart.com">A List Apart</a></Li> <Li><ahref= "http://yuiblog.com">YUI Blog</a></Li> <Li><ahref= "http://blameitonthevoices.com">Blame it on the voices</a></Li> <Li><ahref= "http://oddlyspecific.com">Oddly specific</a></Li></ul>

The JS code is as Follows:

//Classic Event Handling Example(function(){ varresources = document.getElementById (' Resources ')); varLinks = resources.getelementsbytagname (' a '); varall =links.length; for(vari=0;i<all;i++){  //Attach a listener to each linkLinks[i].addeventlistener (' Click ', handler,false); }; functionhandler (e) {varx = e.target;//Get The link that is clickedAlert (x); E.preventdefault (); };}) ();

With event delegation, You can write more gracefully:

(functionvar resources = document.getElementById (' resources '); Resources.addeventlistener (' click ', handler,falsefunction  handler (e) {   var/  get the link tha  if(x.nodename.tolowercase () = = = ' A ') {   alert (' Event delegation: ' + x ');   E.preventdefault ();  } };}) ();
Do you know which version of JavaScript your browser supports?
varJs_ver =[];(Number.prototype.toFixed)? Js_ver.push ("1.5"):false;([].indexof&& [].foreach]? Js_ver.push ("1.6"):false;((function(){Try{[a, b] = [0,1];return true;}Catch(ex) {return false;}}) ())? Js_ver.push ("1.7"):false;([].reduce&& [].reduceright && JSON]? Js_ver.push ("1.8"):false;("". trimleft)? Js_ver.push ("1.8.1"):false; Js_ver.supports=function() {if(arguments[0])return(!! ~ this. Join (). indexOf (arguments[0] + ",") + ","); Else      return( this[ this. length-1]);} Alert ("Latest Javascript version supported:" +js_ver.supports ()); Alert ("support for version 1.7:" + js_ver.supports ("1.7"));
Determine if a property exists
//Bad:this would cause an error in code if foo is undefinedif(foo) {dosomething ();}//good:this doesn ' t cause any errors. however, even when//Foo is set to NULL or false, the condition validates as trueif(typeofFoo! = "undefined") {dosomething ();}//better:this doesn ' t cause any errors and in addition//values NULL or false won ' t validate as Trueif(window.foo) {dosomething ();}

There are cases when we have deeper structures and need more appropriate checks:

// Ugly:we has to proof existence of every // object before we can be sure property actually exists if (window.ofoo && ofoo.obar && oFoo.oBar.baz) {dosomething ();}

In fact, the best way to detect whether a property exists is:

if inch Window) {  Console.log ("OPERA");} Else {  console.log ("not OPERA");}
Detects whether an object is an array
var obj=[];object.prototype.tostring.call (obj)= = "[Object Array]";
Passing objects to a function
functiondosomething () {//Leaves The function if nothing is passed    if(!arguments[0]) {return false; }varOargs = Arguments[0] arg0= Oargs.arg0 | | "", Arg1= Oargs.arg1 | | "", Arg2= Oargs.arg2 | | 0, Arg3= Oargs.arg3 | |[], Arg4= Oargs.arg4 | |false;} DoSomething ({arg1:"foo", Arg2:5, Arg4:false});
Using labels in loops

Sometimes nested loops in loops, you may want to exit a layer of loops, before always using a flag variable to judge, now know there is a better way:

 outerloop:  for  (var  ii=0;ii<5;ii++ if  Span style= "color: #000000;" > (somethingistrue ()) { //  Breaks the  Outer loop Iteration   outerloop; } innerloop:  for  (var  ia=0;ia< 5;ia++ if   (somethingelseistrue ()) { //  Breaks the inner loop iteration  break    innerloop; }}}  

Reprint Address: https://my.oschina.net/os2015/blog/465376

Summary JavaScript Learning summary-tips, methods, details (rpm)

Related Article

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.