JavaScript Programming Learning Skills Summary _javascript Skills

Source: Internet
Author: User

This example for you to share the JavaScript programming learning skills for your reference, the specific contents are as follows

1. Variable Conversion

Varmyvar= "3.14159",

str= "" +myvar,//tostring

int=~~myvar,//tointeger

float=1*myvar,//tofloat

bool=!! Myvar,/*toboolean-anystringwithlength

andanynumberexcept0aretrue*/

Array=[myvar];//toarray

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.

2, take the whole to convert to the numerical 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 ' |

//Result:

All numeric values 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: ten

-2.23456789|0

//Results:-2

3, Date conversion value

JS itself the internal representation of time is the Unix timestamp, in milliseconds the current distance from January 1, 1970 0 O'Clock time Unit

vard=+newdate ();//1295698416792

4, class array object to the array

Vararr=[].slice.call (arguments) The

following example uses the more absolute

functiontest () {

varres=[' item1 ', ' item2 ']

res= Res.concat (Array.prototype.slice.call (arguments))//Method 1

Array.prototype.push.apply (res,arguments)//Method 2

}

5, the conversion between the system

(int). ToString (;//convertsinttohex,eg12=>) "C"

(int). ToString (8);//convertsinttooctal,eg.12=> "14"

parseint (string,16)//convertshextoint,eg. " FF "=>255

parseint (string,8)//convertsoctaltoint,eg." =>16

inserts an array into the location specified by another array

vara=[1,2,3,7,8,9];

varb=[4,5,6];

varinsertindex=3;

A.splice.apply (A,array.prototype.concat (insertindex,0,b));

6. Delete array elements

vara=[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.
7, to determine whether IE

varie=/* @cc_on!@*/false;

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

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

Edithttp://www.lai18.com

//Seemingly is the shortest, the use of IE does not support the standard ECMAScript in the array of the last comma ignored mechanism

varie=!-[1,];

Using the condition annotation of IE,

varie=/* @cc_on!@*/false;

or the conditional annotation

varie//@cc_on =1;

IE does not support vertical tab

varie= ' V ' = = ' V ';

Principle ditto
varie=!+ "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:

VARNUMBERS=[3,342,23,22,124];

varmax=0;

For (Vari=0;i

if (numbers[i]>max) {

max=numbers[i];

}

}

Alert (max);

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

VARNUMBERS=[3,342,23,22,124];

Numbers.sort (function (a,b) {returnb-a});

Alert (numbers[0]);

Of course, the most concise way is:

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

You can do this now.

[Xhtml]view plaincopy

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

Math.min.apply (math,[ 12,123,3,2,433,4])//Take the minimum value

8. Generate Random Number

Math.random (). toString (). substring (2);//tostring () The parameter of the function is 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];

9. Event Delegation

The JS code is as follows:

Classiceventhandlingexample

(function () {

Varresources=document.getelementbyid (' resources ');

Varlinks=resources.getelementsbytagname (' a ');

Varall=links.length;

For (vari=0;i

//attachalistenertoeachlink

links[i].addeventlistener (' click ', Handler,false);

};

Functionhandler (e) {

varx=e.target;//getthelinkthatwasclicked

alert (x);

E.preventdefault ();

};

}) ();

Use event Delegation to write more elegant:

(function () {

Varresources=document.getelementbyid (' resources ');

Resources.addeventlistener (' click ', Handler,false);

Functionhandler (e) {

Varx=e.target;//getthelinktha

if (x.nodename.tolowercase () = = ' A ') {

alert (' Eventdelegation: ' +x);

E.preventdefault ();

}

;

}) ();

10, the detection of IE version

Var_ie= (function () {

varv=3,div=document.createelement (' div '), all=div.getelementsbytagname (' I ');

while (

div.innerhtml= ',

all[0]

);

returnv>4?v:false;

} ());

JavaScript version detection

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];returntrue;} catch (ex) {Returnfalse;}}) ())? 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 ("Latestjavascriptversionsupported:" +js_ver.supports ());

Alert ("Supportforversion1.7:" +js_ver.supports ("1.7"));

11, determine whether the property exists

bad:thiswillcauseanerrorincodewhenfooisundefined

if (foo) {

dosomething ();

}
Good:thisdoesn ' Tcauseanyerrors. However,evenwhen

//fooissettonullorfalse,theconditionvalidatesastrue

if (typeoffoo!= "undefined") {

DoSomething ();

}
BETTER:THISDOESN ' tcauseanyerrorsandinaddition

//valuesnullorfalsewon ' tvalidateastrue

if (window.foo ) {

dosomething ();

}

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

Ugly:wehavetoproofexistenceofevery

//objectbeforewecanbesurepropertyactuallyexists

if (window.oFoo &&ofoo.obar&&ofoo.obar.baz) {

dosomething ();

}

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

if ("opera" Inwindow) {

console.log ("opera");

} else{

console.log ("Notopera");

}

12, detect whether the object is an array

Varobj=[];

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

The above is the entire content of this article, I hope to learn JavaScript program to help you.

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.