Personal summary of some of the JavaScript techniques, utility functions, concise methods, programming details _javascript Skills

Source: Internet
Author: User
Tags return tag

Variable conversion

var myVar  = "3.14159",
str   = "" + myvar,//to string
int.   = ~~myvar,//To integer
float  = 1*my Var,//to float
bool  =!! MyVar,/* to Boolean-any string with length and any number
except 0 are true
*  /array = [MyVar];//To AR Ray


However, the conversion date (new Date (MyVar)) and the regular expression (new RegExp (MyVar)) must use a constructor to use a simplified form such as/pattern/flags when creating regular expressions.

The rounding is converted to a numeric type at the same time

When a character variable participates in an operation, JS automatically converts it to a numeric type (if it cannot be converted to Nan)
    ' 10.567890 ' | 0
    //Result:
    All the numerical types in//js are double-precision floating-point numbers, so In the bitwise operation, JS will first convert these digital arithmetic to integers, and then perform the operation
    //| is binary or, x|0 is always equal to x;^ or, same 0 1, so x^0 is always equal to X, as to ~ is to take the reverse, two times after the value of course is the same
    10.567890 ' ^ 0    
    /Result:
    2.23456789 | 0
    //Results:-2
    ~~-2.23456789
    /Result:-2

Date Turn value

    The internal representation of JS itself time is the Unix timestamp, which in milliseconds records the time unit
    var d = +new Date () of the current distance of January 1, 1970 0 o'clock ();//1295698416792

Class Array Object array

var arr =[].slice.call (arguments)


The following example uses a more absolute

function test () {
  var res = [' item1 ', ' item2 ']
  res = res.concat (Array.prototype.slice.call (arguments))//Method 1
  Array.prototype.push.apply (res, arguments)       //Method 2
}

Transitions between systems

(int). toString (16); converts int to hex, eg => "C"
(int). toString (8);//converts int to octal, eg. => "a"
parseint ( STRING,16)//converts hex to int, eg. "FF" => 255
parseint (string,8)//converts octal to int, eg. "=>" 16

Inserts an array at the location specified by another array

var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertindex = 3;
A.splice.apply (A, Array.prototype.concat (Insertindex, 0, b));

To delete an array element

var a = [1,2,3,4,5];
A.splice (3,1);      A = [1,2,3,5]

You may wonder why you should use splice instead of Delete, because using delete will leave a void in the array, and the subscript below is not decremented.

To determine whether IE

var ie =/* @cc_on!@*/false;

Such a simple words can be judged whether ie, too ...

In fact, there are more wonderful ways, please see the following

Seemingly the shortest, the use of IE does not support the standard ECMAScript in the array at the end of the comma ignore the mechanism of
var ie =!-[1,];
Using IE condition annotation
var ie =/* @cc_on!@*/false;
or the conditional annotation
var ie//@cc_on =1;
IE does not support vertical tab characters
var ie = ' \v ' = ' V ';
Principle above
var ie =!+ "\v1";

To learn this moment feel oneself weak burst.


Try to make use of the native method

To find the maximum 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) {
  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 (a,b) {return b-a});
Alert (numbers[0]);

Of course, the most concise way is:

Math.max (12,123,3,2,433,4); Returns 433

You can do this now.

Math.max.apply (Math, [12, 123, 3, 2, 433, 4])//Fetch maximum
Math.min.apply (math, [12, 123, 3, 2, 433, 4])//min

Generate random numbers

    Math.random (). ToString (). substring (2);//The ToString () function is based on the parameters of the base, and the range is 2~36.
    math.random (). toString. substring (2);

Exchange two variable values without a third party variable

A=[b, b=a][0];

Event delegation

For a simple example: the HTML code is as follows

 
 


The JS code is as follows:

Classic Event Handling Example
(function () {
 var resources = document.getElementById (' resources ');
 var links = resources.getelementsbytagname (' a ');
 var all = Links.length;
 for (Var i=0;i<all;i++) {
  //Attach a listener to each link
  links[i].addeventlistener (' click ', Handler,false) ;
 };
 function Handler (e) {
  var x = e.target;//Get the link this is clicked
  Alert (x);
  E.preventdefault ();
 };
}) ();


Use event Delegation to write more elegant:

(function () {
 var resources = document.getElementById (' resources ');
 Resources.addeventlistener (' click ', Handler,false);
 function Handler (e) {
  var x = e.target//Get the link tha
  if (x.nodename.tolowercase () = = ' A ') {
   alert (' Ev ENT delegation: ' + x ';
   E.preventdefault ();
  }
 ;
}) ();

Detect IE Version

var _ie = (function () {
  var v = 3, div = document.createelement (' div '), all = Div.getelementsbytagname (' i ');
  while (
    div.innerhtml = ' <!--[if GT IE ' + (++v) + ']><i></i><![ Endif]--> ',
    all[0]
  );
  Return v > 4? V:false;
} ());

JavaScript version detection

Do you know which version of JavaScript your browser supports?

var js_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"));

To determine whether a property exists

Bad:this would cause an error into code when foo is undefined
if (foo) {
dosomething ();
}
Good:this doesn ' t cause any errors. However, even when
//foo are set to NULL or false, the condition validates as true
if (typeof foo!= "undefined") {
dosomething ();
}
Better:this doesn ' t cause any errors and in addition
//values NULL or False won ' t validate as true
if Ow.foo) {
dosomething ();
}

In some cases, we have deeper structures and need more appropriate checks when

Ugly:we have to proof existence of every
//object before we can is 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 ("Opera" in window) {
  console.log ("opera");
} else{
  Console.log ("not OPERA");
}

Detects if an object is an array

var obj=[];
Object.prototype.toString.call (obj) = = "[Object Array]";

Passing objects to functions

function dosomething () {
//Leaves The function if it's passed
if (!arguments[0]) {return
false;< c7/>}
var oargs  = 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
});

Passing a function for the Replace method

var sflop  = "flop: [Ah] [Ks] [7c]";
var avalues = {"A": "Ace", "K": "King", 7: "Seven"};
var asuits = {"H": "Hearts", "s": "Spades",
"D": "Diamonds", "C": "Clubs"};
Sflop  = sflop.replace (/\[\w+\]/gi, function (match) {
match  = Match.replace (match[2], asuits[match[2]);  
Match  = Match.replace (match[1], avalues[match[1]] + "of");
return match;
});
String Sflop now contains:
//"flop: [Ace of Hearts] [King of Spades] [Seven of clubs]"

Using labels in loops

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

Outerloop: For
(var ii=0;ii<5;ii++) {
if (somethingistrue ()) {
//Breaks the outer loop iteration
    break Outerloop;
}
Innerloop: For
(var ia=0;ia<5;ia++) {
if (somethingelseistrue ()) {
//Breaks the Inne  R Loop Iteration break
Innerloop;
}
}

To weigh a pair of arrays


* * @desc: Log group to Redo, return a new array without repeating elements
/function unique (target) {
  var result = [];
  Loop:for (var i = 0, n = target.length i < n; i++) {for
    (var x = i + 1; x < n. x + +)
      {if (target[x] = = T Arget[i]) {
        continue loop;
      }
    }
    Result.push (Target[i]);
  return result;
}


Or as follows:


Array.prototype.distinct = function () {
  var newArr = [],obj = {};
  For (var i=0, len = This.length i < len; i++) {
    if (!obj[typeof (this[i)) + This[i]]) {
      Newarr.push (this[i)); C20/>obj[typeof (This[i]) + this[i]] = ' new ';
    }
  }
  return NEWARR;
}

In fact, the best way to do this is


Array.prototype.distinct = function () { 
  var sameobj = function (A, b) { 
    var tag = true; 
    if (!a | |!b) return false; 
    for (Var x in a) { 
      if (!b[x]) return false; 
      if (typeof (a[x] = = = ' object ') { 
        tag = sameobj (A[x],b[x]); 
      } else { 
        if (a[x]!==b[x]) return 
        false; 
    } 
    return tag; 
  var newArr = [], obj = {}; 
  for (var i = 0, len = this.length i < len; i++) { 
    if (!sameobj (obj[typeof (this[i)) + this[i], This[i]) { 
    Newar R.push (This[i]); 
    Obj[typeof (This[i]) + this[i]] = this[i]; 
    } 
  return NEWARR; 
}

Usage examples (borrow comments):

var arr=[{name: "Tom", Age:12},{name: "Lily", Age:22},{name: "Lilei", age:12}];
var newarr=arr.distinct (function (ele) {return
 ele.age;
});

Find the most characters and numbers in a string

var i, Len, maxobj= ', maxnum=0, obj={};
var arr = "SDJKSFSSSCFSSDD";
for (i = 0, len = arr.length i < len; i++) {
  obj[arr[i]]? obj[arr[i]]++: obj[arr[i]] = 1;
  if (Maxnum < Obj[arr[i]]) {
    maxnum = obj[arr[i]];
    Maxobj = Arr[i];
  }
Alert (Maxobj + "appears in the array" + Maxnum + "Times");


In fact, there are many, these are just my free to sum up some of the things.

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.