45 JavaScript Skills Daquan (GO)

Source: Internet
Author: User
Tags case statement setinterval

6. Use typeof, instanceof and constructor with care

    • typeof: Do not forget typeof null returns object, and most objects, typeof (Array, Date, and others) will also return an object
    • Constructor: Internal prototype attribute, can be overwritten (can refer to: Also talk about prototype object)
    • A instanceof:javascript operator that examines the prototype chain of a constructor
var arr = ["A", "B", "C"];typeof arr;   Return "Object" arr  instanceof Array//Truearr.constructor ();  //[]

7. Create a self-executing function

This is often called a self-invocation of an anonymous function or an immediate function expression (iife). When you create it, it automatically executes the function.

(function () {    ///Some private code that would be executed automatically}) ();(function (A, b) {    var result = A+b;    return result;}) (10,20)

8. Get an array item randomly

var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2145, 119]; var  randomitem = Items[math.floor (Math.random () * items.length)];

9. Get a random number within a certain range

x = Math.floor (Math.random () * (Max-min + 1)) + min;

10. Get a numeric array from the number 0 to the maximum value

var numbersarray = [], max = 100; for (var I=1; Numbersarray.push (i++) < Max;);  numbers = [0,1,2,3 ... 100]

11. Generate a random string

function Generaterandomalphanum (len) {    var rdmstring = "";    for (; rdmstring.length < Len; rdmstring  + = Math.random (). toString (. substr (2));    return  rdmstring.substr (0, Len);}

12. To disrupt the order of elements in a numeric array

var numbers = [5, 458, 120,-215, 228, 400, 122205,-85411];
Numbers = Numbers.sort (function () {return math.random () –0.5});
/* The array numbers is equal for example to

[120, 5, 228,-215, 400, 458,-85411, 122205] * *

13, the trim function of string
String.prototype.trim = function () {return this.replace (/^\s+|\s+$/g, "");};

14. Attaching an array to another array
var array1 = [N, "foo", {name: "Joe"},-2458]; var array2 = ["Doe", 555, 100];  Array.prototype.push.apply (Array1, array2);/* Array1 'll is equal to  [N, "foo", {name "Joe"}, -2458, "Doe", 555 , 100] */

15. Convert the arguments object to an array
var Argarray = Array.prototype.slice.call (arguments);

16. Verify whether the parameter is of type number
function Isnumber (n) {    return!isnan (parsefloat (n)) && isfinite (n);}

17. Verify that the parameter is an array
function IsArray (obj) {    return Object.prototype.toString.call (obj) = = = ' [Object Array] ';}

Note that the ToString () method is overridden, and using this technique will not get the desired result. Or you can do this:
Array.isarray (obj); This is the method of a new array

If you are not using multiple frames, you can also use the Instanceof method. But if you have multiple contexts, you will get the wrong result.
var myframe = document.createelement (' iframe ');d ocument.body.appendChild (MyFrame); var myArray = window.frames[window.frames.length-1]. Array;var arr = new MyArray (a,b,10); [a,b,10]//instanceof won't work correctly, MyArray loses he constructor//constructor is not shared between frame Sarr instanceof Array; False

18. Get the maximum and minimum values in a numeric array
var  = [5, 458, -215, 228, Numbers, 122205, -85411];var maxinnumbers = Math.max.apply (Math, numbers); var Mininnumbers = Math.min.apply (Math, numbers);

19. Empty an array
var myArray = [222,];myarray.length = 0; MyArray'll is equal to [].

20. Do not use Delete to delete an array itemUse split instead of using Delte to delete an item in the array. Using delete simply replaces the original item with undefined, not the actual deletion from the array. Do not use the following method
var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];items.length; return 11delete items[3]; return trueitems.length; Return 11/* items equal to [548, "a", undefinedx1, 5478, "foo", 8852, Undefinedx1, "Doe", 2154, 119]
   */

But in the following ways

var items = [548, ' a ', 2, 5478, ' foo ', 8852,, ' Doe ', 2154, 119];items.length; Return 11items.splice (3,1); items.length; Return 10/* items equal to [548, "a", 5478, "foo", 8852, Undefinedx1, "Doe", 2154,119]   */

You should use Delete to delete the properties of an object

21. Use length to truncate an arraySimilar to the way we emptied the array above, we use the Length property to truncate an array.
var MyArray = [N, 222, +, 124, 98,];myarray.length = 4; MyArray'll is equal to [12, 222, 1000, 124].

In addition, if you set the length of an array to a value larger than the current size, then this array will be changed to add a new undefined. The length property of an array is readable and writable.

Myarray.length = 10; The new array length is 10myarray[myarray.length-1]; Undefined

22. Use logical operators in conditions: and, or

var foo = 10;foo = = && dosomething (); Equivalent to if (foo = =) dosomething (); foo = = 5 | | DoSomething (); Equivalent to if (foo! = 5) dosomething ();

Or can be used to set default parameters for a function

function DoSomething (arg1) {    Arg1 = arg1 | | 10;//If Arg1 is not set, ARG1 will be set to 10} by default

23. Use the map () method to iterate through an array of items

var squares = [1,2,3,4].map (function (val) {    return val * val;}); /squares'll be equal to [1, 4, 9, 16]

24. Keep the decimal place

var num =2.443242342;num = num.tofixed (4);  num'll be equal to 2.4432

25, floating point number problem

0.1 + 0.2 = = = 0.3//is false9007199254740992 + 1//are equal to 90071992547409929007199254740992 + 2//are equal to 90071 99254740994

Why is it false? 0.1+0.2 equals 0.30000000000000004. Do not forget that all JavaScript numbers are internally floating numbers in 64-bit binary notation, conforming to the IEEE 754 standard. For more information, you can read this blog post. You can use the toFixed () and Toprecision () methods to solve this problem.

26. When using For-in to traverse an object's internal properties, pay attention to checking

The following code snippet avoids accessing the properties of a prototype while traversing an object property

for (var name in object) {    if (Object.hasownproperty (name)) {        //does something with name    }}

27. Comma operator

var a = 0;var B = (a++); Console.log (a);  A'll is equal to 1console.log (b);  B is equal to 99

28. Cache variables that need to be queried or computed

var navright = document.queryselector (' #right '), var navleft = document.queryselector (' #left '); var navup = Document.queryselector (' #up '); var navdown = Document.queryselector (' #down ');

29, pass the parameter to Isfinite () to verify

Isfinite (0/0); Falseisfinite ("foo"); Falseisfinite ("10"); Trueisfinite (ten);   Trueisfinite (undifined);  Falseisfinite ();   Falseisfinite (null);  True  !!!

30. Avoid negative indexes in arrays

var numbersarray = [1,2,3,4,5];var from = Numbersarray.indexof ("foo");  From is equal To-1numbersarray.splice (from,2);    would return [5]
Ensure that the parameter passed to splice () is not a negative number. 31. Serialization and deserialization of JSON
var person = {name: ' Saad ', age:26, department: {id:15, Name: "R & R"}};var Stringfromperson = Json.stringify (per son);/* Stringfromperson is equal to ' {' name ': ' Saad ', ' age ': ', ' Department ': {' ID ': ' Name ': ' R '}} '   */var personfromstring = Json.parse (Stringfromperson);/* personfromstring is equal to Person object  */

32. Avoid using the eval () and function () constructors

Using the Eval and function constructors is a very expensive operation because each time they invoke the scripting engine to convert the source code into executable code.

var func1 = new Function (functioncode), var func2 = eval (functioncode);

33. Avoid using with

using with () inserts a global variable. Therefore, a variable of the same name can be confused by overriding the value.

34. Avoid looping an array with for-in

Don't use it that way.

var sum = 0;for (var i in arraynumbers) {    sum + = Arraynumbers[i];}

There's a better way

var sum = 0;for (var i = 0, len = arraynumbers.length; i < Len; i++) {    sum + = Arraynumbers[i];}

35. Pass function to settimeout () and setinterval () instead of string

If you pass the string to SetTimeout () or setinterval (), the string will be parsed as if it were using eval, which is very time consuming. Do not use:

SetInterval (' dosomethingperiodically () ', +); SetTimeOut (' Dosomethingafterfiveseconds () ', 5000)

Recommended Use

SetInterval (dosomethingperiodically), SetTimeOut (Dosomethingafterfiveseconds, 5000);

36, use Switch/case statement, not a series of if/else

Using Switch/case is more efficient and more elegant (easier to organize code) than in 2. But do not use switch/case when judging more than 10 kinds of situations.

37. Use Switch/case when judging the range of values

function GetCategory (age) {    var category = "";    Switch (true) {case        IsNaN:            category = ' not ' age ';            break;        Case (age >=):            category = ' old ';            break;        Case (age <=):            category = "Baby";            break;        Default:            category = "Young";            break;    };    return category;} GetCategory (5);  would return "Baby"

38. Specify prototype for the created object

It is possible to write a function to create an object with the specified parameters as prototype:

function Clone (object) {    function Oneshotconstructor () {};    Oneshotconstructor.prototype= object;    return new Oneshotconstructor ();} Clone (Array). prototype;  // []

39. HTML Escape function

function escapehtml (text) {    var replacements= {"<": "<", ">": ">", "&": "&", "\" ":" ""};    Return Text.replace (/[<>& "]/g, function (character) {        return replacements[character];    });}

40. Avoid using try-catch-finally inside the loop

At run time, each time a catch clause is executed, the caught exception object is assigned to a variable, and in the try-catch-finally structure, the variable is created each time. Do not use this:

var object = [' foo ', ' Bar '], i;for (i = 0, len = object.length; I <len; i++) {    try {        //do something this throw S an exception    }    catch (e) {        //Handle exception    }}

It's like this.

var object = [' foo ', ' Bar '], i;try {for    (i = 0, len = object.length; I <len; i++) {        //does something that throw s an exception    }}catch (e) {    //Handle Exception}

41. Set timeout for xmlhttprequests

var xhr = new XMLHttpRequest (); xhr.onreadystatechange = function () {    if (this.readystate = = 4) {        cleartimeout ( Timeout);        Do something with response data    }}var timeout = setTimeout (function () {    xhr.abort ();//Call Error callback }, 60*1000/* Timeout after a minute */); Xhr.open (' GET ', url, true); Xhr.send ();

42. Processing WebSocket Timeout

Usually when the WebSocket connection is established, if there is no activity within 30 seconds, the server pauses the connection, the same reason, the firewall will also pause the connection.

To prevent timeouts, you may need to send an empty message to the server side at intervals. To do this, you can add the following two functions to your code: one to keep the connection and the other to cancel the connection. With this technique, you can control the problem of timeouts.

var Timerid = 0;function keepAlive () {    var timeout = 15000;    if (websocket.readystate = = Websocket.open) {        websocket.send (");    }    Timerid = setTimeout (keepAlive, timeout);} function cancelkeepalive () {    if (timerid) {        canceltimeout (Timerid);    }}

The KeepAlive () method should be added at the end of the OnOpen () method of the WebSocket connection, and cancelkeepalive () is added at the end of the OnClose () method.

43. Remember: primitive operators are always funnier than function calls . Use vanillajs.

For example, do not use this

var min = Math.min (A, b); A.push (v);

Instead, use this instead.

var min = a < b? A b; A[a.length] = v;

44, when coding, to keep the code clean. Compress the code before you go live.

45. JavaScript is excellent: Best Resources to learn JavaScript

      • Code Academy JavaScript Tracks:http://www.codecademy.com/tracks/javascript
      • Eloquent JavaScript by Marjin haverbeke:http://eloquentjavascript.net/
      • Advanced JavaScript by John resig:http://ejohn.org/apps/learn/

45 JavaScript Skills Daquan (GO)

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.