JavaScript base article (3) The reference type of object, function, etc. _javascript tips

Source: Internet
Author: User
Tags local time prev wrapper

Reading Table of Contents

Object type

1, through the constructor to create
2. Creating objects by literal notation

Array type

The same array can also be created in two ways:
If we want to print all the values in the array, we can print the variable name of the array directly:
To add a value to an array:
Stack method, queue method:
About the ordering of arrays:
Some ways to manipulate arrays:
Find Location method
Iterative methods

Merge method

Date type

RegExp type

function type

Three kinds of representations:

Method overload
function Internal properties (arguments and this)

Basic Packing Type

Built-in objects for browsers
URI Encoding method

Summarize

We are in "step-by-Step Learning JavaScript Basics (1): Basic Concepts" The simple introduction of the five basic data types undefined, Null, Boolean, number, and string. Today we mainly introduce the following complex data types (that is, reference data types)

Object type

The most reference types we use are of type object, and it is generally good to store and transmit data. However, do we know the two ways of creating it?

1, through the constructor to create

such as: var obj = new Object ();

There is a very flexible use of reference types in JS, which can be dynamically attached to properties and assignments.

Such as:

var obj = new Object ();
Obj.name = "John"; dynamically add attribute and assign value
obj.age =;
alert (obj.name);

2. Creating objects by literal notation

Now we are using more literal notation to create the object.

Such as:

var obj = {
 name: "John",
 age:23
};
alert (obj.age);

is equivalent to the effect above. In this way create a feeling structure more clear, more packaging feeling. :)

We can still use that.

Such as:

var obj = {};
Obj.name = "John";
Obj.age = n;
alert (obj.age);

Such as:

var obj = {
 ' name ': ' John ',//Add double quotes age:23} to the attribute
;
alert (obj.name);

Are you feeling strong and flexible? I usually point to the property when I visit it, but there is another way.

such as: (We can use the form of brackets to access the property value)

var obj = {
 "name tow": "John",
 age:23
};
Alert (obj.name tow);//There will be an error, the attribute can not have a space
alert (obj["name tow"]);

Cases:

Array type

In addition to object, it should be the most used array. Here's a list of common uses.

The same array can also be created in two ways:

var arr = new Array (1, 2, 3, 4, 5);//Created by constructor

The above two methods are equivalent, we can access the array directly by subscript: alert (arr[2]);.

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

var arr2 = [5, 4, 3, 2, 1];//creates
var str2 = "" by literal expression;
for (var i = 0; i < arr2.length i++) {
 str2 = Arr2[i] + ","
}
alert (STR2);//Print stitching String  
alert (ARR2); Direct print variable name (actually automatically calls the array's ToString method)

Cases:

 var arr2 = [5, 4, 3, 2, 1];//creates
var str2 = "" by literal expression;
for (var i = 0; i < arr2.length i++) {
 str2 + = Arr2[i] + ","
}
alert (STR2);//Print stitching string

Cases:

 var arr2 = [5, 4, 3, 2, 1];//creates
alert (arr2) by literal expression;/Direct print variable name (actually automatically calls the array's ToString method)

The print arr2 directly above, we find that the default is comma-delimited. So sometimes, we don't want to do with commas. Then you might be able to use the Join method.

 var arr2 = [5, 4, 3, 2, 1];//creates
alert (Arr2.join ('_')) by literal expression;/Direct print variable name (actually automatically calls the array's ToString method)

To add a value to an array:

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

There is also a more ingenious way to add value: arr2[arr2.length] = 9; Arr2[arr2.length] = 10; , the subscript length is exactly the next of the maximum length of the array, and length is dynamically automatically accumulated after the value is added.

Stack method, queue method:

What is a stack? (backward first out). What is a queue? (First out), how do we use arrays to mimic the way this data structure is accessed? A diagram below explains the four methods provided by the array object.

As you can see from the diagram, the combination of shift and push, unshift, and pop can be accessed by the stack's data structure, and the combination of SHITF and pop, shift, and unshift can be accessed by the queue's database organization. Note here: While POPs and shift fetch the data, the values in the array are also removed.

Cases:

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

About the ordering of arrays:

The order of the array has sort (positive) reverse (inverse).

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

var arr2 = [5, n, 1];
Alert (Arr2.sort ());

The result is not what we want:

 var arr2 = [5, n, 1];
Alert (Arr2.sort ());

Why is that? Because sort does not directly compare numeric types, the comparison is made to string. So what do we want to compare numbers for? We can send a function to sort, for example:

 function Mycompare (O1, O2)
{return
 o1-o2;//if positive, the O1 is large, the negative number is O2, and zero is equal.
}
var arr2 = [5, n, 1];
Alert (Arr2.sort (Mycompare));

  Someone will ask O1 and O2 How did they get here? This is specified by the sort function. It may not be acceptable to say so. Next, we'll simulate the sort order, and we'll see.

var arr2 = [5, 14, 23, 12, 1, 123, 23, 4, 5, 6, 32, 5, 3, 2, 1]; Arr2.mysort = function (fun) {//********************* specific sort 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) {//Here's the method we're passing in to determine whether to sort the swap position.
    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 rule)} 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 sort 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) {//Here's the method we're passing in to determine whether to sort the swap position.
   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 rule)} alert (Arr2.mysort (Mycompare));

Of course, what we simulate is not so good, that's probably what it means.

The reverse sequence is simple: (direct reverse () is OK)

function Mysort (O1, O2)
{return
 o1-o2;//if positive, the O1 is large, the negative number is O2, and zero is equal.
}
var arr2 = [5, n, 1];
Arr2.sort (mysort);
Arr2.reverse ();
alert (ARR2);

Some ways to manipulate arrays:
Concat creates a new copy and merges the incoming arguments

var colors = ["Red", "green", "Blue"];
var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]);
alert (colors); Red,green,blue
alert (colors2);//red,green,blue,yellow,black,brow

Slice creates a new copy, takes the location data of the array

var colors = ["Red", "green", "blue", "yellow", "purple"];
var colors2 = Colors.slice (1);//From the beginning of subscript 1 to the end
var colors3 = Colors.slice (1, 4);//From Subscript 1 (contains 1) to 4 (does not contain 4)
alert ( COLORS2); Green,blue,yellow,purple
alert (COLORS3);//green,blue,yellow

Splice will change the original array data to achieve the deletion, interpolation and substitution of the logarithm group.

 var colors = ["Red", "green", "Blue"];
 var removed = colors.splice (0, 1); Delete the first item (starting with subscript 0, delete 1 items)
 alert (colors);//Green,blue
 alert (removed);//red, the returned array contains only one
 removed = Colors.splice (1, 0, "yellow", "orange"); Inserts two items starting at position 1 (starting with subscript 0, deleting 0 items, and inserting the following parameter data)
 alert (colors);//Green,yellow,orange,blue
 alert (removed); Returns an empty array
 removed = Colors.splice (1, 1, "Red", "purple");//Insert two items, delete an item (starting with subscript 1, delete 1 [i.e. yellow], and insert the following parameter data)
 alert (colors); Green,red,purple,orange,blue
 alert (removed);//yellow, the returned array contains only one item

Find Location method

IndexOf () and LastIndexOf () are looking for positions in the array, similar to the corresponding method in string.

Iterative methods

every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.
filter (): Each item in an array runs the given function, returning an array of items that the function returns True.
foreach (): Runs the given function for each item in the array. This method has no return value.
map (): Each item in an array runs the given function, returning an array of the results of each function call.
some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

None of the above methods modifies the contained values in the array.

Such as:

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

which foreach and map are not very different, just one has a return value, one does not. In practice we use foreach more, and we simulate the implementation of foreach below.

 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 completely simulate our own implementation ******* 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 completely simulate our own implementation ******* 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

Reduce () and reduceright (), these two methods are more interesting, have never been contacted before. First look at the example, and then explain:

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

is also a cycle, the first execution prev is 1, cur is 2. The second time, the Prev is 3 (the result of 1 plus 2), and Cur is 3 (the third of the array). This process lasts until each item in the array is accessed, and the result is returned. Reduceright just in the opposite direction.

Here's how to simulate:

var numbers = [1, 2, 3, 4, 5, 3];
var sum = numbers.reduce (function (prev, cur, index, array) {return prev + cur;}); Simulation implementation 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) {RE
Turn 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;}); Simulation implementation reduce************************** Numbers.myreduce = function (fun) {for (var i = 0; i < n Umbers.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) {R
Eturn prev + cur; Alert ("sum:" + sum + "sum2:" + sum2); //

Date type

We often need to test the performance of a function to take its execution in time:

Get start time
var start = Date.now ();
Call function
dosomething ();
Get stop time
var stop = Date.now (), result
= Stop–start;

Some common methods are listed below

GetTime () returns the number of milliseconds to represent the date; The value returned by the valueof () method is the same
SetTime (ms) sets the date in milliseconds, changing the entire date
getFullYear () gets a 4-digit year (such as 2007 instead of just 07)
getUTCFullYear () returns the 4-digit year of the UTC date
setFullYear (year) sets the year of the date. The incoming year value must be a 4-digit number (such as 2007 instead of just 07)
setUTCFullYear (year) sets the year of the UTC date. The incoming year value must be a 4-digit number (such as 2007 instead of just 07)
GetMonth () returns the month of the date, where 0 indicates January, and 11 means December
getUTCMonth () returns the month in UTC date, where 0 indicates January, and 11 means December
Setmonth (month) sets the month of the date. The month value passed in must be greater than 0, and more than 11 to increase the year
setUTCMonth (month) sets the month of the UTC date. The month value passed in must be greater than 0, and more than 11 to increase the year
GetDate () returns the number of days in the date month (1 to 31)
getUTCDate () returns the number of days in the UTC date month (1 to 31)
Setdate (day) sets the number of days in the date month. If the value passed in exceeds the number of days that should be in the month, increase the month
setUTCDate (day) sets the number of days in the UTC date month. If the value passed in exceeds the number of days that should be in the month, increase the month
Getday () Returns the day of the week (0 of Sunday, 6 means Saturday)
getUTCDay () Returns the day of the week of the UTC date (0 of which is Sunday, and 6 means Saturday)
GetHours () returns the number of hours in the date (0 to 23)
getUTCHours () returns the number of hours in UTC date (0 to 23)
Sethours (time) set the number of hours in the date. Increases the number of days in the month when the value passed in exceeds 23
setUTCHours (time) sets the number of hours in UTC date. Increases the number of days in the month when the value passed in exceeds 23
Getminutes () returns the number of minutes in the date (0 to 59)
getUTCMinutes () returns the number of minutes in UTC date (0 to 59)
Setminutes (min) Set the number of minutes in the date. Increase the number of hours by passing in a value of more than 59
setUTCMinutes (sub) Sets the number of minutes in the UTC date. Increase the number of hours by passing in a value of more than 59
Getseconds () returns the number of seconds in the date (0 to 59)
getUTCSeconds () returns the number of seconds in UTC date (0 to 59)
Setseconds (SEC) sets the number of seconds in the date. An incoming value of more than 59 will increase the number of minutes
setUTCSeconds (SEC) sets the number of seconds in the UTC date. An incoming value of more than 59 will increase the number of minutes
Getmilliseconds () returns the number of milliseconds in the date
getUTCMilliseconds () returns the number of milliseconds in UTC date
Setmilliseconds (milliseconds) set the number of milliseconds in a date
setUTCMilliseconds (milliseconds) set the number of milliseconds in UTC date
getTimezoneOffset () returns the number of minutes that the local time differs from the UTC time. For example, American Eastern Standard Time returns 300. This value will change when a place enters daylight saving time.

RegExp type

Two kinds of representations:

var pattern1 =/at/g; 

The following arguments represent the pattern, such as: G: Represents the global mode, I: denotes case-insensitive (case-insensitive) mode, M: multiple-line (multiline) mode

Regarding the regular understanding is not very clear, the latter has the opportunity in the individual study to collate regular this piece.

function type

Three kinds of representations:

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

All of the above three kinds are feasible, but we usually use more is the first, the second is useful, the third is used relatively little, but the most can see the essence of function, is actually a function object instance.

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

Alert (SUM1 (1, 2));/Popup value 3
alert (sum2 (1, 2));//Report exception [sum2 is not a function]
function sum1 (NUM1, num2) {return NUM1 + num2;
var sum2 = function (NUM1, num2) {return num1 + num2;};

Because the JS parser is from the top to the bottom of the parsing, in the implementation of the SUM2 has not been defined, so reported an exception. But the sum1 is more special, is the affirmation type. Pre-resolution (function declaration elevation) is performed before Sum1 is executed. The equivalent of the SUN1 definition to the top of the source tree.

Method overload

Strictly speaking, JS is not a method of overloading, but we can be based on the number of parameters to simulate. (also, the parameters of the function in JS we are uncertain type)

Cases:
The above does not appear as we expected, because the second definition of SUN1 is not an implementation overload, but rather a direct overwrite of the first definition. Below, we will simply simulate the implementation of the method overload:

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 properties (arguments and this)

Arguments: Class Array object that contains all the arguments in the Passed-in function. The following simulation overloads are implemented by arguments:

function sum (num, num, num) {
 var temp =;
 if (arguments.length = =) {
  //*********** specifically implements its logical ********************* for
  (var i =; i < arguments.length; i++) {
   temp + = arguments[i]
  ;
 }
 else {
  //*********** specifically implements its logical ********************* for
  (var i =; i < arguments.length; i++) {
   temp = Argu Ments[i];
  }
 return temp;
}
Alert ("+ +" + sum (,) + "++=" + sum (,,));

 function sum1 (NUM1, num2, num3) {
var temp = 0;
if (arguments.length = = 3) {
//*********** specifically implements its logical ********************* for
(var i = 0; i < arguments.length; i++) {
temp + = arguments[i]
;
}
else {
//*********** specifically implements its logical ********************* for
(var i = 0; i < arguments.length; i++) {
temp = AR Guments[i];
}
return temp;
}
Alert ("1+2=" + sum1 (1, 2) + "1+2+3=" + sum1 (1, 2, 3));

We have a question in the first blog post:

Six

 var fun = function (NUM1) {
  if (num1 <= 1) {return
   1;
  }
  else {return
   NUM1 * Fun (NUM1-1);
  }
 }
 var fun2 = fun;
 Fun = function () {return
  1;
 }
 

However, there are no students to answer, some people may feel too simple, or not willing to bother to answer. The answer to this question is:

Why is this the answer? It seems to be different from what we expected. Here we illustrate:

We may have found a problem, which is that the 4th call is not the function itself (that is, there is no recursion), this is not what we want. What we want is that, no matter how the outside changes, 4 of them represent the function pointer. Then we can use the arguments callee method, for example:

Another internal property of the function this:

First, let's look at a problem:

var color = "Red";
var o = {color: "Blue"};
function Saycolor () {
 alert (this.color);
}
Saycolor (); "Red"
o.saycolor = Saycolor;
O.saycolor (); "Blue"

Why would there be different results? We remember the word "which object points out the method, this is which object". The example above is actually equivalent to:

Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
 alert (this.color);
}
Window.saycolor (); "Red"
o.saycolor = Saycolor;

Although "which object points out the method, this is which object", but sometimes we do not want such a result, we do not want to use the object point or object to point out that this is another object. Then we can use call:

The first parameter, as passed, is assigned directly to this within the function. and call similar have apply, the difference look below:

 var o = {color: "Blue"};
 var O2 = {color: "red"};
 function Saycolor (A, b) {
  alert (This.color + A + b);
 }
 Saycolor.apply (O, [1, 2]);//Only two arguments, the first is the object assigned to this, and the second is the function real parameter group
 saycolor.call (O2, 1, 2);//You can pass multiple arguments, the first is the object assigned to this value , the following is a comma-separated function argument

Basic Packing Type

In the first installment of this series, there is a question:

Four

var obj1 = {}; Obj1.name2 = "John";
var str1 = "Test"; Str1.name2 = "Dick";
Alert (obj1.name2 + "" + str1.name2);

Why is this the result? Because the str1.name2 sets the value, it accesses the string wrapper class and then accesses the str1.name2 before the previous wrapper class has been destroyed.

Why should there be packing class?

Because you can manipulate the basic data types like an action reference object, such as: var S1 = "some text"; var s2 = s1.substring (2);

What are the basic types of wrapper classes?

Boolean, number, and string types.

Built-in objects for browsers

Global (which is actually the window we usually use) and math (some computational functions)

URI Encoding method

encodeURI, encodeURIComponent, decodeURI, decodeuricomponent
//encodeuri encode the full URL (the space will be encoded as%20). To the decoding decodeURI "
Alert" (Window.encodeuri ("Http://i.cnblogs.com/EditPosts.aspx?postid = 5002381"));
encodeURIComponent will have all the special characters in the URL transcoding (so we are generally used to do partial URL transcoding, such as the parameters in the URL) "corresponding decoding decodeuricomponent"
alert ( Window.encodeuricomponent ("Http://i.cnblogs.com/EditPosts.aspx?postid = 5002381"));
Eval

This is one of the most powerful functions in JS, relative to a separate parser. As I do in the example of the operation is implemented using this function.

Such as:

 <textarea class= "Test_code" style= "width:%;height:px; max-height:px; " >
//..... This inside writes JS code
var obj = {}; obj.name = "John";
var str = "Test"; Str.name = "Dick";
Alert (Obj.name + "" + str.name);
 </textarea>
 <input type= "button" class= "Test_code_but" onclick= "eval ($ (this). Prev (). Val ());" Value= " Run the/>

Effect Chart:

Of course, you also introduce the Jqeruy problem, blog park by default has been introduced. So, you don't have to introduce it again, you don't see the alert frame when you test it, because the blog park is banned. I do it in the Dialog dialog box in the jquery UI.

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.