"JS Foundation--1" A record of some basic knowledge and skills

Source: Internet
Author: User

This digest from Mdn:https://developer.mozilla.org/zh-cn/docs/web/javascript/a_re-introduction_to_javascript

1, by the following rules, any value can be converted to a Boolean type:

1) false , 0 ,, empty string (),,, "" NaN null and undefined both are converted tofalse

2) Other values will be converted totrue

This feature can be applied directly to the judgment statement, reducing the amount of code.

2. Define an object in the object

1 var obj = {2     name: "Carrot", 3     "for": "Max", 4     Details: {5         color: "Orange", 6         size:127     }8}

3, array.length not the number of accurate elements in the index group, as follows:

var a = ["Dog", "cat", "hen"];a[100] = "Fox"; a.length101

4. Efficient notation for traversing arrays

The traditional way to iterate through an array is as follows:

for (var i = 0; i < a.length; i++) {    //does something with A[i]}

This is a little less efficient, because each cycle is calculated one length at a time. The improved methods are:

for (var i = 0, len = a.length; i < Len; i++) {    //does something with A[i]}

A better way to do this is:

for (var i = 0, item; item = A[i]; i++) {    //does something with item}

Here we use two variables. The expression for the middle part of the For loop is still used to monitor whether it is true-if successful, then the loop continues. Because i each increment of 1, each element of the array is passed to the item variable in order. When a "falsy" element (such as undefined ) is found, the loop ends. Note that this technique can only be used if you confirm that the array does not contain a value of "Falsy". If you want to traverse an array that may contain 0 or an empty string, you should use i, j the notation instead.

Another way to iterate through an array is to use for...in loops. Note that if someone Array.prototype adds a new property to it, they will also be traversed through such loops:

for (var i in a) {  //does something with A[i]}

5, if you want to add elements after an array, the safest way is:

a[a.length] = item;                 // 与 a.push(item)等效;
because it a.length is an array that is larger than the maximum index value of an array, you can guarantee that you assign an empty position to the new element at the end of the array.

6, the array class contains many methods:

a.toString(), a.toLocaleString(), a.concat(item, ..), a.join(sep),a.pop(), a.push(item, ..), a.reverse(), a.shift(), a.slice(start, end),a.sort(cmpfn), a.splice(start, delcount, [item]..), a.unshift([item]..)
    • concatReturns a new array that adds the element at the end.
    • popRemoves and returns the last element.
    • pushAdd one or more elements at the end of the array (similar to ar[ar.length] )
    • sliceReturns a sub-array
    • sortSort an array
    • spliceRemove part of the array and replace it with other values
    • unshiftStitching elements to the beginning of an array

7, we can know that the function can be passed an indefinite number of parameters, to get all the parameters can be:

The function can access an inner object named arguments in the function body, which, like an array-like object, includes the values of all the passed-in functions. Let's rewrite the above function so that he can receive as many values as we expect.

function Add () {    var sum = 0;    for (var i = 0, j = arguments.length; I < J; i++) {        sum + = Arguments[i];    }    return sum;} > Add (2, 3, 4, 5) 14

8. Anonymous functions can even be done directly:

(function () {    var b = 3;    A + = b;}) ();

9, how to handle the recursive invocation of anonymous functions (because they do not have an actual name)? The answer is through the arguments object, the object that is used to refer to a series of parameters, and it also provides a arguments.callee property named. This is usually a pointer to the current (called) function, so it can be used for recursive invocation:

var charsinbody = (function (Elm) {    if (Elm.nodetype = = 3) {//Text_node        return elm.nodeValue.length;    }    var count = 0;    for (var i = 0, child; child = Elm.childnodes[i]; i++) {        count + = Arguments.callee (child);    }    return count;}) (document.body);

10. Through the prototype (prototype) can rewrite or add object methods and properties, such as:

>var s = "Simon";> s.reversed () TypeError on line 1:s.reversed was not a function> String.prototype.reversed = fun Ction () {    var r = "";    for (var i = this.length-1; I >= 0; i--) {        R + = This[i];    }    return r;} > s.reversed () nomis

11, about the Apply () and call () method, not commonly used but it is necessary to understand, there is time to say.

12. Closed Package

What we'll see below is one of the most powerful structures in JavaScript that cannot be mentioned: closures. But it also has a lot of potential problems. So what exactly does it do?

function makeAdder(a) {    return function(b) {        return a + b;    }}x = makeAdder(5);y = makeAdder(20);x(6)?y(7)?

  makeAdderThe name of the function itself should reveal a lot of secrets: it creates a new ' adder ' function, which itself takes a parameter, which is added to the arguments passed in by the outer function when it is called.

What happens here is very similar to the inline function described earlier: a function is defined inside another function, and an intrinsic function can access the variables of the external function. The only difference here is that the external function is returned, so common sense tells us that the local variable "should" no longer exist. But they still exist--otherwise the Adder function will not work. That is, there are makeAdder two different "replicas" of local variables-one is a equal to 5 and the other is a equal to 20. So the results of those functions are as follows:

x(6) // 返回 11y(7) // 返回 27

Here is what actually happened. Whenever JavaScript executes a function, it creates a ' scope object ' and is used to hold the local variables created in the function. It is initialized with the variable passed into the function. This is similar to global object, which holds all global variables and functions, but there are some very important differences: first, each time the function is executed, a new, specific scope object is created; second, the Global object (in the browser as window object to access), you can access the scope object directly from the JavaScript code. There is currently no mechanism to traverse the properties within the current scope object.

So when called makeAdder , a scope object is created with a property that is passed into the function as a a parameter makeAdder . makeAddera newly created function is then returned. Typically, the JavaScript garbage collector cleans up the makeAdder created scope object at this point, but the returned function retains a reference to that Range object. As a result, the scope object will not be reclaimed by the garbage collector until the makeAdder reference count of the returned function object is zero.

The scope object consists of a chain called the range chain. It is similar to the prototype (prototype) chain, and is used by the JavaScript object system.

A closure is a combination of a function and a Range object in the function being created.

Closures allow you to save state-so they can usually be used in place of objects.

13. Memory leaks

"JS Foundation--1" A record of some basic knowledge and skills

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.