The JavaScript that must be known

Source: Internet
Author: User
Tags variable scope

This article transferred from: http://www.cnblogs.com/xsyblogs/p/3938521.html

JavaScript is the front-end prerequisite, and this one of the essence is too much, recently in the review of some things are relatively easy to ignore, here record, on the one hand is to hope that they can be handy in peacetime application, on the other hand also hope to bring a little bit of harvest.

one, JavaScript = = and = = =, that is, the equality operator and the equivalent operator.

The equality operator, if the operand has the same type, determines its equivalence, returns True (equal) if the value of the two operands is equal, otherwise returns false (unequal);

If the types are different, the following is the case:

null and undefined are equal, numbers are compared to string characters, strings are converted to numbers, and one is converted to 1 for true and then compared; if one value is an object and the other is a number or a string, The object is converted to the original value (via ToString () or the valueof () method), and the other returns false.

The equivalent operator, if the operand type is not the same, returns false directly, with the same type as the following judgment:

1, is the number, if the value is the same, then the two equals but Nan, because Nan and itself are not equal, otherwise;

2, are the case of strings: the value of unequal is not equal, otherwise equivalent;

3, are Boolean value, are True/false is equal otherwise not equal;

4, if the two operands refer to the same object (array or function) is equivalent, otherwise unequal;

5, the null/undefined is equal.

Second, function scope

Scopes are manifested in all languages, except in JavaScript scripts. The scope of the-->javascript is valid within the function body, and there is no block scope. In Java or C #, we can write the following loops:

 Public void method (String obj1,string obj2) {for (int i=0;i<obj1.length;i++) {// do  something} // i is undefined at this time  for (int i=0;i<obj2.length;i++) {//doanother thing}

And in JavaScript, it's different:

function func () {for (var i = 0; i < array.length; i++) {//dosomething here.
    }// at this time I still have values, and i = = Array.Lengthprint (i); // i = = Array.Length;}


function func () {for (var i = 0; i < Array.Length; i++) {//do something. At this time I still have values, and i = = Array.lengthprint (i);//i = = Array.Length;}

JavaScript functions are run within local scopes, and function bodies running within local scopes can access variables and functions of their outer layers, which may be global scope. The scope of JavaScript is lexical scope, so-called lexical scope is that its scope is defined at the time of definition (lexical analysis), but not at execution time, as in the following example:

var str = "global"= "local";p rint (str);} Scopetest ();

What do you think is the result of the operation? Global local or local local or other? And the right result is undefined local, yes, undefined local!

The first print (str) returns a undifined error because the scopetest variable str is pre-accessed in the definition of the function, and then the STR variable is initialized. So why does the function not visit the external str variable at this time? This is because, at the end of the lexical analysis, when the scope chain is constructed, the var variable defined in the function is placed in the chain, so str is visible within the entire function scopetest (from the first line of the function body to the last line), because the STR variable itself is undefined, the program is executed sequentially, The first line will return undefined, the second behavior str is assigned, so the third row of print (str) will return "local".

three, array operation

Commonly used operations for array:

Contact () joins two or more arrays and returns the result

Join () Places all elements of an array into a string, separated by the specified delimiter

Pop () deletes and returns the last element corresponding to push (), adds one or more elements to the end of the array, and returns a new length; similar to the stack and the stack

Reverse () Reverses the order of the elements

Shift () deletes and returns the first element

Slice () returns an array from an existing array

Sort () sorts the array elements, by default alphabetically, or by numerical size: Array.Sort (A, B) {return-A-b});

Splice () Delete element and add new element

Unshift () adds one or more elements to the beginning of the array and returns the new length

ValueOf () returns the original value of the array object

Four, JavaScript closure characteristics

Let's look at an example where it's hard to find a reason if you don't understand JavaScript features:

var outter == ["One", "one", "one", "three", "four"];  for (var i = 0; i < array.length;i++== = = function () {print (i);} Outter.push (x);}} // Call this function clousetest ();p rint (outter[0].invoke ());p rint (outter[1].invoke ());p rint (outter[ 2].invoke ());p rint (outter[3].invoke ());

What is the result of the operation? 0 1 2 3? This is the answer many people expect, but is that really the case? Run right now, are you stunned? It turned out to be 4 4 4 4!

In fact, at each iteration, such a statement x.invoke = function () {print (i);} is not executed, just constructs a function body as "print (i);" Function object, that's all. When i=4, the iteration stops, the external function returns, and when the Outter[0].invoke () is called again, the value of I is still 4, so that the invoke of each element in the Outter array returns the value of I: 4. How to fix it, we can declare an anonymous function, and then execute it immediately.

= ["One", "one", "one", "three", "four"];  for (var i = 0; i < array.length;i++== = = function (no) {return  function () {print (no);}} (i); Outter.push (x);}}

In this example, when we assign a value to X.invoke, we run a function that returns a function and execute it immediately, so that every time the iterator is X.invoke, it executes the same sentence:

// x = = 0x.invoke = function () {print (0);} // x = = 1x.invoke = function () {print (1);} // x = = 2x.invoke = function () {print (2);} // x = = 3X.invoke = function () {print (3);}

This will give you the right results.

You can determine the type of a given object based on Object.prototype.toString.Call (source). There are also two additional places to note:

1, if the variable scope is inside the function, then the external cannot be accessed , such as:

var person=function () {var name= "Default"; return {getname:function () {return  name;},setname:function (NO) {name=No}}} ();p rint (person.name)//undefined

2. References

References are also interesting topics, and the references in JavaScript always point to the final object, not the reference itself, let's look at an example:

var obj = {}; // null object var ref = obj; // reference obj.name = "Objecta";p rint (ref.name); // ref then adds the Name property , obj = ["One", "one", "three"]; // obj points to another object (array object)print (ref.name); // ref also points to the original object print (obj.length); // 3print (ref.length); // undefined

Operation Result:

Objecta
Objecta
3
Undefined

obj is simply a reference to an anonymous object, so ref does not point to it, and when obj points to another array object, the reference ref does not change and always points to the "empty" object "{}" that later added the Name property. After understanding this, the following example is not difficult:

var obj = {}; // creates a new object and is referenced by obj as var ref1 = obj; // ref1 refers to obj, which is in fact the null object referenced by obj var ref2 ="function";p rint (ref1.func);p rint (ref2.func);

Declare an object, then refer to the object with two references, then modify the original object, noting the order of the two steps, which runs:

function
function

As we can see from the running result, it should be noted that after a reference has been defined, modifying the original object affects its reference.

These are some of the most recently found in the wrong place, but also hope that you can meet the problem of the wrong to share, learn together and progress together!

The JavaScript that must be known

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.