Analysis of confusing variable assignment _javascript techniques in JavaScript

Source: Internet
Author: User
JavaScript is a weakly typed language, declaring a variable without declaring its type, and Var x can be equal to any type of value.
Like what:

var str = "string ...";
var arr = [' This ', ' is ', ' array '];
var obj = {name: "Caizhongqi", Age:26,sex: "Male"};
These are all right, which seems very simple and convenient, but this convenience also brings some unpredictable surprises to see below (Example 1):

<script> var x = "This is string";
var y = x;
X= "Ni Hao";
Alert (y)
</script>

You may know at once that alert is the "This is string", yes, but for the Java language programmer, var y=x should assign x to the Y variable in the memory address (pointer), so they think it should alert the "Ni Hao" will be more in line with the Java language habits, but the JavaScript language is not the case, string assignment is a direct operation, the data copy directly to the storage space Y.

Take another look at the following example (Example 2):

<script>
var x = ["Hello"]//This is an array with only one element, and the element is a string type
var y = x;
X[0] = "World";
Alert (y[0]);
</script>

If you think that alert is "Hello", it's wrong. When var y = x, does x not already have its array given to Y? But in fact it is not so, when var y = x, x is the address of its memory (pointer)! X[0]= "World" modifies the data at the original storage location, so alert (Y[0]) is the new value of X to get out of alert. Messed up, huh? How to be a direct amount for a while is a reference quantity?
No hurry, the following example will be more confusing (example 3):

<script>
var x = ["Hello"]//This is an array with only one element, and the element is a string type
var y = x;
x = ["Ni", "Hao"]; X will become a new array.
Alert (y[0]);
</script>

Your eyes tell you that alert is "Hello"! It's an elusive javascript!.

Stephen Chow's "homemade 00 paint" in a similar scene:
When the star ye just from Shenzhen to Hong Kong to carry out the task, Shing from his baggage found a blow the hair of the wind, star Ye said this is actually a must planing, take out a look at the leather shoes is a wind, a seemingly mobile phone is actually a need to plane. Need to plane and the wind Shing and the audience have messed up, ha ha, this is I like a piece of film, the first time to look at the belly laugh pain.

Look back and see just the variable assignment, the direct volume and the use of reference, it is like a plane and the wind drum for change, we are dizzy.
In fact, the problem is in the second assignment x = ["Ni", "Hao"] on X, we look at the variables changing on the memory and the JavaScript treats the string type differently from the object type:

We observe the following two cases:
var x = "This is string ...";
var y = [' This ', ' is ', ' string '];

The difference between x and Y is the type, the JavaScript parser assigns the string directly (in fact, copy) to X (the direct amount), but assigns the array pointer to Y (the reference quantity), all of which are instantaneous and fully automatic! Combined with the following diagram, you might be better able to understand:



In the picture P1, p2 ... Is the pointer to the variable, and the y in the Var y above is the pointer P1 (assuming) of the object type variable, and x holds the string itself. To analyze example 3, to execute var x = ["Hello"], the parser creates a storage space on the memory to put the array, and X gets the address of the space (the pointer), and then executes x = ["Ni", "Hao"], and the parser opens up a new storage space for the new array, and X is the A pointer to a new storage space, that is to say, the redefinition (or redistribution) of a variable in JavaScript will create a new storage space without destroying the original space; Look back at the example 2,x[0] = "World", this sentence does not give X a new definition of value, no new storage space, It only modifies the data in its storage space, so the last alert in Example 2 is "world"; Example 1 is a string assignment, and the whole process is a direct amount operation.

As you can see from the above analysis, JavaScript variables can be stored directly or stored pointers, this is no way to be manually disturbed, therefore, in the day-to-day coding, you need to pay attention to these issues, such as the large string connection, the circulation inside the assignment and other details can directly affect the execution efficiency of the program.

Take a look at two examples:

var _tmpstr= "";
var str = "This are big string ...";
For (i=0 i<100; i++) {
_tmpstr + A;
}
A = _TMPSTR;

Because it is a string operation, using the direct amount, each loop must operate a large string, very cumbersome, inefficient. If you use a reference operation instead, you pass an array:

var str = "This are big string ...";
var _tmparray = [];
For (i=0 i<100; i++) {
_TMPARRAY[I]=STR;
}
str = _tmparray.join ("");

To do a test, if there is a 100k string, with a direct volume connection operation, my machine needs about 2600 milliseconds, if the array connection, it will take 150 milliseconds, the efficiency difference more than 10 times times.

Long time no write such a lengthy article, it took me half a day.

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.