JavaScript usage Tips

Source: Internet
Author: User
Tags return tag

Read Catalogue

    • Variable conversions
    • Rounding and converting to numerical type
    • Date to Value
    • Class Array object to array
    • Conversion between the binaries
    • Inserts an array into the location specified by another array
    • To delete an array element
    • Determine if it is IE
    • Try to use native methods
    • Generate random numbers
    • Exchange values of two variables without a third-party variable
    • Event delegation
    • Detect IE Version
    • JavaScript version detection
    • Determine if a property exists
    • Detects whether an object is an array
    • Passing objects to a function
    • Passing a function for the Replace method
    • Using labels in loops
    • De-weight The array
    • Find the most characters and the number of occurrences in a string
Variable conversions
1234567 varmyVar   = "3.14159",str     = ""+ myVar,//  to stringint     = ~~myVar,  //  to integerfloat   = 1*myVar,  //  to floatbool    = !!myVar,  /*  to boolean - any string with lengthand any number except 0 are true */array   = [myVar];  //  to array

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 the operation, JS automatically converts it to a numeric type (if it cannot be converted, to Nan)        ' 10.567890 ' | 0        //results:        all the numerical values inside the//JS are double-precision floating-point numbers, so when JS is doing bit arithmetic, Will first convert these numeric operands to integers, and then perform the operation        //| is binary or, x|0 is always equal to x;^ for XOR, the same as 0 different 1, so x^0 is always equal to X; As for the ~ is the bitwise negation, two times after the value of course is the same        ' 10.567890 ' ^ 0                //Results:        2.23456789 | 0        //Results:-2        ~~-2.23456789        //Results: 2
Date to Value
        The internal representation of the time of JS itself is the UNIX timestamp, which records the current distance from January 1, 1970 0 O'Clock of the time unit        var d = +new date () in milliseconds;//1295698416792
Class Array object to array
1 vararr =[].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}
Conversion between the binaries
1234 (int).toString(16); // converts int to hex, eg 12 => "C"(int).toString(8);  // converts int to octal, eg. 12 => "14"parseInt(string,16) // converts hex to int, eg. "FF" => 255parseInt(string,8) // converts octal to int, eg. "20" => 16
Inserts an array into 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 want to use splice instead of Delete, because using delete will leave an empty hole in the array, and the underlying subscript is not decremented.

Determine if it is IE
1 varie = /*@cc_on [email protected]*/false;

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

In fact, there are more wonderful methods, please see below

Seems to be the shortest, using IE does not support the standard ECMAScript array in the end of the comma-ignored mechanism var ie =!-[1,];//take advantage of IE conditional comment var ie =/*@[email protected]*/false;//or conditional comment var i e//@cc_on =1;//IE does not support vertical tab var ie = ' \v ' = = ' V ';//principle above var ie =!+ "\v1";

The moment I learned this, I felt weak.

Try to use native methods

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

12345678 varnumbers = [3,342,23,22,124];var max = 0;for(vari=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

123 varnumbers = [3,342,23,22,124];numbers.sort(function(a,b){returnb - a});alert(numbers[0]);

Of course, the simplest way is:

1 Math.max(12,123,3,2,433,4); // returns 433

You can do that now.

        Math.max.apply (Math, [12, 123, 3, 2, 433, 4])//MAX        Math.min.apply (Math, [12, 123, 3, 2, 433, 4])//Take min
Generate random numbers
        Math.random (). ToString (+). substring (2);//The ToString () function has a base and a range of 2~36.        math.random (). toString (+). substring (2);
Exchange values of two variables without a third-party variable
A=[b, b=a][0];

One of the ways to quote comments:

A^=b, B^=a, a^=b;
Event delegation

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 that is clicked    Alert (x);    E.preventdefault ();  };}) ();

With event delegation, you can write more gracefully:

(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 {[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 when 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 (typeof foo! = "undefined") {Dosomet Hing ();} Better:this doesn ' t cause any errors and in addition//values NULL or false won ' t validate as Trueif (Window.foo) {D Osomething ();}

There are situations where we have deeper structures and need more appropriate checks when

Ugly:we has to proof existence of every//object before we can is sure property actually Existsif (Window.ofoo && Amp 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 whether an object is an array
12 varobj=[];Object.prototype.toString.call(obj)=="[object Array]";
Passing objects to a function
function dosomething () {//Leaves the function if nothing is passed if (!arguments[0]) {return false; } 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 the loop is nested, you may want to exit a layer of loops, before always using a marker variable to judge, now know 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 inner loop iteration Brea  K Innerloop; }  }}
De-weight The array
123456789101112131415 /**@desc:对数组进行去重操作,返回一个没有重复元素的新数组*/functionunique(target) {    varresult = [];    loop: for(vari = 0, n = target.length; i < n; i++) {        for(varx = i + 1; x < n; x++) {            if(target[x] === target[i]) {                continueloop;            }        }        result.push(target[i]);    }    returnresult;}

Or as follows:

12345678910 Array.prototype.distinct = function() {    varnewArr = [],obj = {};    for(vari=0, len = this.length; i < len; i++){        if(!obj[typeof(this[i]) + this[i]]){            newArr.push(this[i]);            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; }

Examples of use (borrowing 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 the number of occurrences 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");

JavaScript usage Tips

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.