JavaScript Small notes Classic algorithm, etc...

Source: Internet
Author: User

1. Use the parameters inside the ToString () to achieve a quick conversion between the various binaries:
var n = 17;binary_string = n.toString(2);//->二进制"10001"octal_tring = n.toString(8);//->八进制"021"hex_string = n.toString(16);//->十六进制"0x11"
2.parseInt () can accept the second optional parameter, which is the cardinality of the specified number conversion, and the legal value range is 2~36. (binary)
parseInt(‘11‘, 2); //->3 (1*2 + 1)parseInt(‘ff‘, 16); //->255 (15*16 + 15)parseInt(‘zz‘, 36); //->1295 (35*36 + 35)parseInt(‘077‘, 8); //->63 (7*8 + 7)parseInt(‘077‘, 10); //->77 (7*10 +7)
3. Declaration in advance (at the time of pre-compilation)

: All variables declared in the JavaScript function, but not assigned, are ' ahead ' to the top of the function body. A local variable in the body of a function overrides a global variable of the same name. (JavaScript does not have block-level scopes)

4. When declaring a variable with VAR, the variable is not configurable, meaning that the variable cannot be deleted by the delete operator. 5. Unary addition (+) and unary subtraction (-) unary addition (+): The unary addition operator converts the operand to a number or Nan and returns the converted number. If the operand itself is a number, the number is returned directly. (used to simply convert ' numeric strings ' to numbers) unary subtraction (-): When '-' is used as a unary operator, it converts the operand to a number as needed, and then changes the symbol of the result of the operation. 6.NaN and any value do not want to wait, including it itself.

By x!===x to determine if X is Nan, the result of this expression is true only if X is Nan. (Use isNaN () to determine if a variable is Nan)

7.Infinity (Infinity),-infinity (infinitely small) 8.JavaScript implementation of several sorting algorithms. 1> Fast Sorting algorithm:
/*快速排序法*/        function quickSort(a) {                if (a.length <= 1) {                        return a;                }                var midLength = Math.floor(a.length / 2);                var midValue = a.splice(midLength,1);                var left = [];                var right = [];                for (var i = 0; i < a.length; i++) {                        if (a[i] < midValue) {                                left.push(a[i]);                        } else {                                right.push(a[i]);                        }                }                return quickSort(left).concat(midValue,quickSort(right));        }        console.log(quickSort([1,5,3,6,2,4,0]));
2> Bubble Sorting algorithm:
/*冒泡排序法*/        function bubbleSort(a) {                var length = a.length;                var sortArray;                for (var i = 0; i < length-1; i++) {                        for (var j = 0; j < length-i-1 ; j++) {                                if (a[j] > a[j+1]) {                                        sortArray = a[j];                                        a[j] = a[j+1];                                        a[j+1] = sortArray;                                }                        }                }                return a;        }        console.log(bubbleSort([2,1,3,6,5,4,7,0]));
3> Insertion Sorting algorithm:
/*插入排序法*/        function insertSort(a) {                var length = a.length;                var sortArray;                for (var i = 1; i < length; i++) {                        for (var j = 0; j < i ; j++) {                                if (a[i] < a[j]) {                                        sortArray = a[i];                                        a[i] = a[j];                                        a[j] = sortArray;                                }                        }                }                return a;        }        console.log(insertSort([0,6,5,3,4,2,1,7]));
4> Selection Sorting algorithm:
/*选择排序法*/        function selectSort(a) {                for (var i = 0; i < a.length; i++) {                        var min = a[i];                        var k = i;                        for (var j = i + 1; j < a.length; j++) {                                if (min > a[j]) {                                        min = a[j];                                        k = j;                                }                        }                        a[k] = a[i];                        a[i] = min;                }                return a;        }        console.log(selectSort([5,1,4,0,3,2,7,6]));
9) do not use try-catch-finally inside the loop

The catch section in Try-catch-finally assigns an exception to a variable when it is executed, which is constructed as a new variable within the runtime scope.

Avoid:

    var object = [‘foo‘, ‘bar‘], i;    for (i = 0, len = object.length; i < len; i++) {        try {            // do something that throws an exception        }        catch (e) {            // handle exception        }    }

Instead, you should:

    var object = [‘foo‘, ‘bar‘], i;    try {        for (i = 0, len = object.length; i <len; i++) {            // do something that throws an exception        }    }    catch (e) {        // handle exception    }
10) Note set timeout when using xmlhttprequests

XMLHttpRequests at execution time, when there is no response for a long time (such as a network problem, etc.), the connection should be aborted and the work can be done through settimeout ():

    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();

It is also important to note that you should not initiate multiple xmlhttprequests requests at the same time.

11) Handling WebSocket Timeouts

Typically, after a websocket connection is created, if there is no activity within 30 seconds, the server will time out the connection, and the firewall can time out the connection with no active connections for the unit cycle.

To prevent this from happening, you can send an empty message to the server at a certain time. You can implement this requirement by using these two functions, one for keeping the connection active and the other for ending the state.

    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 () function can be placed on the last side of the OnOpen () method of the WebSocket connection, and cancelkeepalive () is placed at the very end of the OnClose () method.

12) Note that the original operator is faster than the function call

For example, generally don't do this:

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

This can be replaced by:

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

JavaScript Small notes Classic algorithm, etc...

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.