The JavaScript that must be known

Source: Internet
Author: User
Tags variable scope

In the original: JavaScript that must be known

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 at this time is undefined  for  (int  I=0 ; I<obj2.length;i++ // Span style= "color: #008000;" >do Another thing   
View Code

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;}
View Code

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"; function scopetest () {print (str); var str = "local";p rint (str);} Scopetest ();
View Code

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:

varOutter = [];functionclousetest () {varArray = ["One", "one", "three", "four"]; for(vari = 0; I < array.length;i++){varx ={};x.no=I;x.text=Array[i];x.invoke=function() {print (i);} Outter.push (x);}}//Call this functionclousetest ();p rint (outter[0].invoke ());p rint (outter[1].invoke ());p rint (outter[2].invoke ());p rint (outter[3].invoke ());
View Code

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.

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

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 = = 0 function () {print (0);} // x = = 1 function () {print (1);} // x = = 2 function () {print (2);} // x = = 3 function () {print (3);}
View Code

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
View Code

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 = {}; // Empty 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
View Code

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 var ref1 = obj; // ref1 references obj, which is actually a null object referenced by obj var ref2 == "function";p rint (ref1.func);p rint (ref2.func);
View Code

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.