JavaScript Learning Summary-tips, practical functions, concise methods, programming details

Source: Internet
Author: User
Tags return tag variable scope

Some of the skills of the JavaScript, more practical functions, common function implementation methods, only for reference

Variable conversions

Edit http://www.lai18.com var MyVar  = "3.14159", str   = "" "+ myvar,//   to Stringint = ~~myvar,//To Integerfloa T  = 1*myvar,//to Floatbool  =!! MyVar,/* to Boolean-any string with Lengthand any number except 0 is 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 the edit http://www.lai18.com//character variable participates in the operation, JS automatically converts it to a numeric type (if it cannot be converted and becomes Nan)    ' 10.567890 ' | 0    //Results:/    / JS inside all numerical types are double-precision floating-point number, so, JS in the bit operation, will first convert these numeric operands to an integer, and then perform the operation    //| is binary or, x|0 always equal to x;^ is different or, the same 0 different 1, so x^0 or always equals X; As for the ~ is the bitwise negation And after two times the value of course is the same as    ' 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

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}



Conversion between the binaries

(int). toString (16); converts int to hex, eg: + = "C" (int). toString (8); converts int to octal, eg. "Parseint" (string,16)//converts hex to int, eg. "FF" = 255parseInt (string,8)//converts octal to int, eg. "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



var ie =/* @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

Edit http://www.lai18.com//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's conditional comment var ie =/*@[email prot ected]*/false;//or conditional comment var ie//@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:

var numbers = [3,342,23,22,124];var max = 0;for (var i=0;i<numbers.length;i++) {if (Numbers[i] > max) {  max = Numbe Rs[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 simplest way is:

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];



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 (' Event 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

var obj=[];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": "Spa Des "," 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

/** @desc: An array is de-iterated, returning a new */function with no duplicate elements (target) {  var result = [];  Loop:for (var i = 0, n = target.length; i < n; i++) {for    (var x = i + 1; x < n; + +) {      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]); C14/>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");



In fact, there are many, these are just my idle to summarize some of the nothing.

More JavaScript Learning Collation reference:


1 Regular Summary: regular expressions in JavaScript

Types of variables in 2JavaScript

3 in-depth knowledge of javascript scope issues

4JavaScript Quest: For Loop (for Loops)

5JavaScript Quest: For-in cycle (for-in Loops)

6JavaScript Quest: Prototypes is too powerful

7JavaScript Quest: Var pre-resolution and side effects

8JavaScript Quest: Use global variables with caution

9JavaScript Quest: The importance of writing maintainable code

10 how we should get to know how JavaScript engines work

11JavaScript Quest: Named Function expressions

12JavaScript Quest: Function names in the debugger

13JavaScript Quest: Memory Management for JScript

14JavaScript Quest: function declaration and function expression

15JavaScript Quest: Bugs in JScript

16JavaScript Quest: eval () is "the Devil"

17JavaScript Quest: Basic Coding Specifications

18JavaScript Quest: Use parseint () for numeric conversions

19JavaScript Quest: Constructor Constructor

20 execution Context One: Variable object and active object

21JavaScript Quest: Prototype chain Prototype chain

22 Execution Context Second: scope chain scope Chains

23JavaScript Quest: Object

24JavaScript Quest: SpiderMonkey's Quirks

25JavaScript Quest: Named Function expression substitution scheme

26JavaScript function Second: function expression

27JavaScript function Four: function constructor

28JavaScript function One: function declaration

29JavaScript function Three: function expression in grouping

30JavaScript Quest: A powerful prototype and prototype chain

31 execution context Its four: this pointer

32 execution context Its three: closure Closures

33JavaScript Variable Object Three: Two stages of the execution context

34JavaScript Variable Object second: Vo in different execution contexts

35JavaScript Variable object four: about variables

36JavaScript Variable Object one: VO's declaration

37JavaScript Variable object Its five: __parent__ property

38JavaScript scope chain Three: scope chain characteristics

39JavaScript Scope Chain Second: The life cycle of a function

40JavaScript scope chain One: scope chain definition

41JavaScript Closure Second: implementation of closures

42JavaScript Closures One: Introduction to Closures

43JavaScript closures Its three: the use of closures

Access and traversal of 44JavaScript objects

45JavaScript variable pre-parsing feature

46 New JavaScript data structure streams

47 talking about the anonymous function of JavaScript

48 brief description of JavaScript classes and objects

49JavaScript Some methods for defining classes and objects

50 creating a JavaScript hash table hashtable

Features of 51JavaScript closures

52 talking about the prototype property of JavaScript

The use of the 53JavaScript keyword return

How the 54JavaScript implements inheritance

55 Clear up JavaScript object-oriented thinking

56 in-depth JavaScript object creation details

57 Exploring JavaScript Event bubbling

58 Do you know JavaScript non-blocking load scripts?

Prototype method extension for 59JavaScript date

How 60JavaScript prototype works behind the scenes

611 blog posts with a panoramic view of JavaScript

62 Understandable JavaScript Variable scope

63 Gossip JavaScript and cookies

641 Examples of JavaScript reflection use

65 Analysis of JavaScript garbage collection mechanism

66 non-blocking JavaScript scripting and extension knowledge

Imitation implementation of inheritance mechanism in 67JavaScript

68JavaScript Understanding the lexical scope first to understand closures

69 in-depth study of JavaScript event mechanisms

70 Understanding the function of JavaScript

71JavaScript Object Learning Notes

72[javascript Secret Garden] One of the objects: usage and properties

73[javascript Secret Garden] object second: Prototype

JavaScript Learning Summary-tips, practical functions, concise methods, programming details

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.