JavaScript BASICS (3) reference types such as objects and functions _ javascript skills

Source: Internet
Author: User
This article mainly introduces reference types such as Object and Function in JavaScript BASICS (3). For more information, see Reading directory

Object Type

1. Create a constructor
2. Create an object using literal notation

Array type

Array can also be created in two ways:
If we want to print all values in the array, print the variable name of the array directly:
Add a value to the array:
Stack method and queue method:
Sorting of Arrays:
Operations on Arrays:
Location Search Method
Iteration Method

Merge Method

Date type

RegExp type

Function Type

Three Representations:

Method overload
Function internal attributes (arguments and this)

Basic packaging type

Browser built-in objects
URI encoding method

Summary

In step-by-step javascript BASICS (1): basic concepts, we briefly introduce five basic data types: Undefined, Null, Boolean, Number, and String. Today, we will mainly introduce complex data types (that is, reference data types)

Object Type

The most referenced type we use is the object type, which is generally used to store and transmit data. However, do we know the two creation methods?

1. Create a constructor

For example, var obj = new Object ();

The reference type in js has a very flexible usage, and can dynamically add attributes and assign values.

For example:

Var obj = new Object (); obj. name = "zhangsan"; // Add attributes dynamically and assign values to obj. age = 23; alert (obj. name );

2. Create an object using literal notation

Now, most people use the literal representation to create objects.

For example:

Var obj = {name: "James", age: 23}; alert (obj. age );

It is equivalent to the above effect. In this way, the sensory structure is clearer and more encapsulated. :)

We can also use

For example:

Var obj = {}; obj. name = "James"; obj. age = 23; alert (obj. age );

For example:

Var obj = {"name": "James", // Add double quotation marks age: 23} to the attribute; alert (obj. name );

Does it feel powerful and flexible? I usually click the access attribute, but there is another way.

For example: (we can use brackets to access attribute values)

Var obj = {"name tow": "James", age: 23}; // alert (obj. name tow); // an error is reported here. The attribute cannot contain spaces. alert (obj ["name tow"]); // The attribute will pop up normally.

Example:

Array type

Except for the object, it should be the most used array. Below is a list of common usage.

Array can also be created in two ways:

Var arr = new Array (1, 2, 3, 4, 5); // create var arr2 = [5, 4, 3, 2, 1] through the constructor; // create with a literal expression

The above two methods are equivalent. We can directly access the array through the following method: alert (arr [2]);.

If we want to print all values in the array, print the variable name of the array directly:

Var arr2 = [5, 4, 3, 2, 1]; // create var str2 = ""; for (var I = 0; I <arr2.length; I ++) {str2 + = arr2 [I] + ","} alert (str2); // print the spliced string alert (arr2 ); // print the variable name directly (in fact, the toString method of the array is automatically called)

Example:

Var arr2 = [5, 4, 3, 2, 1]; // create var str2 = ""; for (var I = 0; I <arr2.length; I ++) {str2 + = arr2 [I] + ","} alert (str2); // print the concatenated string

Example:

Var arr2 = [5, 4, 3, 2, 1]; // use a literal expression to create alert (arr2 ); // print the variable name directly (in fact, the toString method of the array is automatically called)

Print arr2 directly above, and we find that all are separated by commas by default. So sometimes we don't want to use commas. Then you may use the join method.

Var arr2 = [5, 4, 3, 2, 1]; // use a literal expression to create alert (arr2.join ('_')); // print the variable name directly (in fact, the toString method of the array is automatically called)

Add a value to the array:

We can directly: arr2 [4] = 7; arr2 [5] = 8;

There is also a more clever way to add values: arr2 [arr2.length] = 9; arr2 [arr2.length] = 10;, the subscript length is just the next of the maximum length of the array, after the value is added, the length is automatically accumulated again.

Stack method and queue method:

What is stack? (Later, first, first, and foremost ). What is a queue? (First-in-first-out), how do we use arrays to simulate this data structure access method? The following figure illustrates the four methods provided by the array object.

From the figure, we can see that the combination of shift and push, unshift and pop can achieve access to the data structure of the stack. The combination of shitf and pop, shift and unshift can achieve access to the data organization of the queue. Note: When pop and shift are used to retrieve data, the values in the array are also removed.

Example:

 var arr2 = [5, 4, 3, 2, 1];alert("arr2.pop:" + arr2.pop() + " arr2:" + arr2);

Sorting of Arrays:

The sorting of arrays includes sort (positive) reverse (reverse ).

Let's take a look at the example and guess the result:

var arr2 = [5, 14, 23, 12, 1];alert(arr2.sort());

However, the results are not what we want:

 var arr2 = [5, 14, 23, 12, 1];alert(arr2.sort());

Why? Because sort does not directly compare the numeric type, it is converted to string for comparison. How can we compare numbers? We can pass functions to sort, for example:

Function mycompare (o1, o2) {return o1-o2; // if it is a positive number, it is o1, negative is o2, and zero is equal .} Var arr2 = [5, 14, 23, 12, 1]; alert (arr2.sort (mycompare ));

Someone will ask how o1 and o2 came from? This is defined by the sort function. This may be unacceptable. Next, we will simulate the sorting of sort by ourselves, and you will understand.

Var arr2 = [5, 14, 23, 12, 1,123, 23, 4, 5, 6, 32, 5, 3, 2, 1]; arr2.mysort = function (fun) {// ********************** specific sorting process ************* * ***** for (var I = 0; I <arr2.length-1; I ++) {for (var j = 0; j <arr2.length-I; j ++) {if (fun (arr2 [j], arr2 [j + 1])> 0) {// use the method we passed in to determine whether to sort and change the location var temp = arr2 [j]; arr2 [j] = arr2 [j + 1]; arr2 [j + 1] = temp ;}}} //************************************** * ************ return arr2 ;} function mycompare (o1, o2) {return o1-o2; // callback function (Specific comparison rules)} alert (arr2.mysort (mycompare); var arr2 = [5, 14, 23, 12, 1,123, 23, 4, 5, 6, 32, 5, 3, 2, 1]; arr2.mysort = function (fun) {// ********************** specific sorting process ************* * ***** for (var I = 0; I <arr2.length-1; I ++) {for (var j = 0; j <arr2.length-I; j ++) {if (fun (arr2 [j], arr2 [j + 1])> 0) {// use the method we passed in to determine whether to sort and change the location var temp = arr2 [j]; arr2 [j] = arr2 [j + 1]; arr2 [j + 1] = temp ;}}} //************************************** * ************ return arr2 ;} function mycompare (o1, o2) {return o1-o2; // callback function (Specific comparison rules)} alert (arr2.mysort (mycompare ));

Of course, what we simulate is not so good. That is probably the meaning.

Reverse Order is simple: (directly reverse)

Function mysort (o1, o2) {return o1-o2; // if it is a positive number, it is o1, negative is o2, and zero is equal .} Var arr2 = [5, 14, 23, 12, 1]; arr2.sort (mysort); arr2.reverse (); alert (arr2 );

Operations on Arrays:
Concat creates a new copy and merges the passed parameters.

var colors = ["red", "green", "blue"];var colors2 = colors.concat("yellow", ["black", "brown"]);alert(colors); //red,green,bluealert(colors2); //red,green,blue,yellow,black,brow

Slice creates a new copy to retrieve the array location data

Var colors = ["red", "green", "blue", "yellow", "purple"]; var colors2 = colors. slice (1); // starts from the subscript of 1 and ends with var colors3 = colors. slice (1, 4); // from subscript 1 (including 1) to 4 (excluding 4) alert (colors2); // green, blue, yellow, purplealert (colors3); // green, blue, yellow

Splice changes the original array data to delete, insert, and replace arrays.

Var colors = ["red", "green", "blue"]; var removed = colors. splice (0, 1); // Delete the first item (from subscript 0, delete 1 item) alert (colors); // green, blue alert (removed ); // red, the returned array contains only one removed = colors. splice (1, 0, "yellow", "orange"); // insert two items starting from position 1 (starting from subscript 0, deleting 0 items, insert the following parameter data) alert (colors); // green, yellow, orange, blue alert (removed); // return an empty array removed = colors. splice (1, 1, "red", "purple"); // insert two items and delete one item (from subscript 1, delete one item [that is, yellow], insert the following parameter data) alert (colors); // green, red, purple, orange, blue alert (removed); // yellow, the returned array contains only one

Location Search Method

IndexOf () and lastIndexOf () are the locations in the array, which are similar to the corresponding methods in the string.

Iteration Method

Every (): run the given function for each item in the array. If this function returns true for each item, true is returned.
Limit filter (): If you run a given function for each item in the array, returning this function returns an array consisting of true items.
Aggregate forEach (): run the given function for each item in the array. This method does not return values.
Evaluate map (): runs a given function for each item in the array and returns an array composed of the results of each function call.
Required some (): run the given function for each item in the array. If this function returns true for any item, true is returned.

The preceding methods do not modify the values contained in the array.

For example:

var numbers = [1,2,3,4,5,4,3,2,1];var everyResult = numbers.every(function(item, index, array){return (item > 2);});alert(everyResult); //false

. ForEach is slightly different from map, but one has a returned value and the other has no. In reality, we use forEach more. Below we simulate the implementation of forEach.

Var str = "", str2 = ""; var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; numbers. forEach (function (item, index, array) {str + = item + "_";}); // ************** in fact, we can simulate and implement it ourselves ******* numbers. myforEach = function (fun) {for (var I = 0; I <numbers. length; I ++) {fun (numbers [I], I, numbers) ;}} numbers. myforEach (function (item, index, array) {str2 + = item + "*";}) //************************************** * ************ alert ("str: "+ str +" str2: "+ str2); var str =" ", str2 =" "; var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; numbers. forEach (function (item, index, array) {str + = item + "_";}); // ************** in fact, we can simulate and implement it ourselves ******* numbers. myforEach = function (fun) {for (var I = 0; I <numbers. length; I ++) {fun (numbers [I], I, numbers) ;}} numbers. myforEach (function (item, index, array) {str2 + = item + "*";}) //************************************** * ************ alert ("str: "+ str +" str2: "+ str2 );

Merge Method

The reduce () and reduceRight () methods are interesting and have never been used before. Let's look at the example and explain it again:

var values = [1,2,3,4,5];var sum = values.reduce(function(prev, cur, index, array){ return prev + cur;});alert(sum); //15

It is also a loop. the first execution of prev is 1 and cur is 2. The second time, prev is 3 (the result of 1 plus 2), and cur is 3 (the third entry of the array ). This process will continue until each item in the array is accessed and the final result is returned. ReduceRight is only in the opposite direction.

The following is a simulation:

Var numbers = [1, 2, 3, 4, 5, 3]; var sum = numbers. reduce (function (prev, cur, index, array) {return prev + cur ;}); // ************************ simulate the implementation of reduce ************ * ************* numbers. myreduce = function (fun) {for (var I = 0; I <numbers. length; I ++) {var temp = 0; for (var j = 0; j <I; j ++) temp + = numbers [j]; var tempNum = fun (temp, numbers [I], I, numbers);} return tempNum ;} //************************************** * ********* var sum2 = numbers. myreduce (function (prev, cur, index, array) {return prev + cur;}) alert ("sum:" + sum + "sum2:" + sum2 ); // var numbers = [1, 2, 3, 4, 5, 3]; var sum = numbers. reduce (function (prev, cur, index, array) {return prev + cur ;}); // ************************ simulate the implementation of reduce ************ * ************* numbers. myreduce = function (fun) {for (var I = 0; I <numbers. length; I ++) {var temp = 0; for (var j = 0; j <I; j ++) temp + = numbers [j]; var tempNum = fun (temp, numbers [I], I, numbers);} return tempNum ;} //************************************** * ********* var sum2 = numbers. myreduce (function (prev, cur, index, array) {return prev + cur;}) alert ("sum:" + sum + "sum2:" + sum2 );//

Date type

We often need to test the performance of a function. We can take its execution time as follows:

// Obtain the start time var start = Date. now (); // call the function doSomething (); // obtain the stop time var stop = Date. now (), result = stop-start;

Some common methods are listed below

GetTime () indicates the number of milliseconds of the date. It is the same as the value returned by the valueOf () method.
SetTime (MS) sets the date in milliseconds, which changes the entire date.
GetFullYear () gets a 4-digit year (for example, 2007 rather than 07)
GetUTCFullYear () returns the four-digit year of the UTC date
SetFullYear (year) sets the year of the date. The input year value must be a four-digit number (for example, 2007, not only 07)
SetUTCFullYear (year) sets the year of the UTC date. The input year value must be a four-digit number (for example, 2007, not only 07)
GetMonth () returns the month in the date, where 0 represents January, and 11 represents December.
GetUTCMonth () returns the month in UTC, where 0 indicates January 1, January, and 11 indicates January 1, December.
SetMonth sets the month of the date. The input month value must be greater than 0. If the value exceeds 11, the year is increased.
SetUTCMonth (month) sets the month of the UTC date. The input month value must be greater than 0. If the value exceeds 11, the year is increased.
GetDate () returns the number of days in the month of the date (1 to 31)
GetUTCDate () returns the number of days in the month of UTC date (1 to 31)
SetDate (day) specifies the number of days in the month of the date. If the input value exceeds the number of days in the month, the number of months is increased.
SetUTCDate (day) sets the number of days in the month of UTC date. If the input value exceeds the number of days in the month, the number of months is increased.
GetDay () returns the day of the week in the date (0 indicates Sunday, 6 indicates Saturday)
GetUTCDay () returns the day of the week in UTC (0 indicates Sunday, 6 indicates Saturday)
GetHours () returns the hour in the date (0 to 23)
GetUTCHours () returns the hour in UTC (0 to 23)
SetHours (hour) sets the hours in the date. If the input value exceeds 23, the number of days in the month is increased.
SetUTCHours (hour) sets the hours in UTC. If the input value exceeds 23, the number of days in the month is increased.
GetMinutes () returns the number of minutes in the date (0 to 59)
GetUTCMinutes () returns the number of minutes in UTC (0 to 59)
SetMinutes (minute) sets the number of minutes in the date. If the input value exceeds 59, the number of hours is increased.
SetUTCMinutes (minute) sets the number of minutes in UTC. If the input value exceeds 59, the number of hours is increased.
GetSeconds () returns the number of seconds in the date (0 to 59)
GetUTCSeconds () returns the number of seconds in UTC (0 to 59)
SetSeconds (seconds) sets the number of seconds in the date. If the input value exceeds 59, the number of minutes is increased.
SetUTCSeconds (seconds) sets the number of seconds in UTC. If the input value exceeds 59, the number of minutes is increased.
GetMilliseconds () returns the number of milliseconds in a date.
GetUTCMilliseconds () returns the number of milliseconds in UTC.
SetMilliseconds (MS) sets the number of milliseconds in a date.
SetUTCMilliseconds (MS) sets the number of milliseconds in UTC.
GetTimezoneOffset () returns the number of minutes between the local time and the UTC time. For example, the US east Standard Time returns 300. This value will change when a certain place enters the region.

RegExp type

Two representations:

var pattern1 = /at/g; var re = new RegExp("cat", "g"); 

The following parameters represent the mode. For example, g: indicates the global mode, I: indicates the case-insensitive mode, and m: indicates the multiline mode.

I don't know much about regular expressions. I will have the opportunity to learn and sort out regular expressions in the future.

Function Type

Three Representations:

function sum (num, num) { return num + num; } var sum = function(num, num){ return num + num; }; var sum = new Function("num", "num", "return num + num"); 

The above three methods are feasible, but we usually use the first method, the second method is also useful, and the third method is rarely used, but we can see the essence of the function most, it is actually an instance of a Function object.

Let's take a look at the differences between 1 and 2.

Alert (sum1 (1, 2); // the pop-up value is 3 alert (sum2 (1, 2 )); // an error is reported. [sum2 is not a function] function sum1 (num1, num2) {return num1 + num2;} var sum2 = function (num1, num2) {return num1 + num2 ;};

An exception is reported because the js parser is parsed from top to bottom and is not defined when sum2 is executed. However, sum1 is special and declarative. The pre-resolution will be performed before the execution of sum1 (function declaration is upgraded ). It is equivalent to putting the sun1 definition at the top (put on the top of the source code tree ).

Method overload

Strictly speaking, js does not provide method overloading, but we can simulate it based on the number of parameters. (Also, we are not sure about the type of the parameters of functions in js)

Example:
The above does not show the expected results, because the second defined sun1 is not an implementation overload, but directly covers the first definition. Next, we will simply simulate implementation method overloading:

function sum1(num1, num2, num3) { if (num1 != undefined && num2 != undefined && num3 != undefined) {  return num1 + num2 + num3; } else if (num1 != undefined && num2 != undefined)  return num1 + num2;}alert(sum1(1, 2));alert(sum1(1, 2, 3));

Function internal attributes (arguments and this)

Arguments: array object of the class, which contains all parameters in the input function. The following uses arguments to implement the above simulated overload:

Function sum (num, num, num) {var temp =; if (arguments. length =) {// *********************************** (var I =; I <arguments. length; I ++) {temp + = arguments [I] ;}} else {// ************ specific implementation of its logic ********************* for (var I =; I <arguments. length; I ++) {temp + = arguments [I] ;}} return temp;} alert ("+ =" + sum (,) + "++ =" + sum (,); function sum1 (num1, num2, num3) {var temp = 0; if (arguments. length = 3) {// *********************************** (var I = 0; I <arguments. length; I ++) {temp + = arguments [I] ;}} else {// ************ specific implementation of its logic ********************* for (var I = 0; I <arguments. length; I ++) {temp + = arguments [I] ;}} return temp;} alert ("1 + 2 =" + sum1 (1, 2) + "1 + 2 + 3 =" + sum1 (1, 2, 3 ));

In the first blog, we asked a question:

VI,

Var fun = function (num1) {if (num1 <= 1) {return 1 ;}else {return num1 * fun (num1-1) ;}} var fun2 = fun; fun = function () {return 1;} alert (fun2 (5); // What is displayed here?

However, no one answered the question. Some people may think it is too simple or unwilling to answer the question. The answer to this question is:

Why is this answer? It seems different from what we expected. The diagram below:

We may have discovered a problem, that is, the function itself is not called in step 1 (that is, there is no recursion), and this is not what we want. What we need is that no matter how the outside changes, four points represent the function pointer. We can use the callee method of arguments, for example:

Another internal property of the function, this:

First, let's look at this problem:

var color = "red";var o = { color: "blue" };function sayColor() { alert(this.color);}sayColor(); //"red"o.sayColor = sayColor;o.sayColor(); //"blue"

Why are there different results? We remember one sentence. Generally, "which object is the method of vertex? this is the object ". The above example is actually equivalent:

window.color = "red";var o = { color: "blue" };function sayColor() { alert(this.color);}window.sayColor(); //"red"o.sayColor = sayColor;o.sayColor(); //"blue" 

Although "the method of which object is clicked, this is the object", sometimes we do not want such a result, we don't want to use object points or object points to think that this is another object. Then we can use call:

The first parameter to be passed as an example is directly assigned to this in the function. Apply is similar to call. The difference is as follows:

Var o = {color: "blue"}; var o2 = {color: "red"}; function sayColor (a, B) {alert (this. color + a + B);} sayColor. apply (o, [1, 2]); // only two parameters are passed. The first is the object that assigns a value for this, and the second is the sayColor array of function arguments. call (o2, 1, 2); // multiple parameters can be passed. The first one is the object that assigns a value for this, followed by a comma (,) for the function arguments.

Basic packaging type

There is a problem in the first article of this series:

IV,

Var obj1 = {}; obj1.name2 = "Zhang San"; var str1 = "test"; str1.name2 = "Li Si"; alert (obj1.name2 + "" + str1.name2 );

Why is this? Because the string packaging class is accessed when str1.name2 is set, and the previous packaging class has been destroyed before str1.name2 is accessed again.

Why is there a packaging class?

Because the basic data type can be operated like the referenced object, for example, var s1 = "some text"; var s2 = s1.substring (2 );

Which basic types are packaging?

Boolean, Number, and String types.

Browser built-in objects

Global (actually the window we usually use) and Math (some computing functions)

URI encoding method

EncodeURI, encodeURIComponent, decodeURI, and decodeURIComponent // encodeURI encode the complete url (space will be encoded as % 20) [decode URI] alert (window. encodeURI ("http:// I .cnblogs.com/EditPosts.aspx? Postid = 5002381 "); // encodeURIComponent will transcode all the special characters in the url (therefore, we generally use this feature for partial url transcoding, such as Url parameters) [corresponding decodeURIComponent] alert (window. encodeURIComponent ("http:// I .cnblogs.com/EditPosts.aspx? Postid = 5002381 "); eval

This is the most powerful function in Javascript. It is relatively independent of a parser. For example, the Operation instance in my article is implemented using this function.

For example:

 //.... Js Code var obj ={}; obj. name = "Zhang San"; var str = "test"; str. name = "Li Si"; alert (obj. name + "" + str. name ); 

:

Of course, you have introduced jqeruy by default in the blog. Therefore, you do not need to introduce it again. If you test it, you will not see the alert bullet box, because the blog Park is disabled. I am using the Dialog box in jquery ui.

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.