About the reference type of JS __js

Source: Internet
Author: User
Tags date1 prev
one about reference variables and basic data variables

In JS contains 5 basic data types: Number,boolean,String, null,undefined.
The most notable thing here is string, which is a reference type in Java.
These five basic data types are accessed by value because you can manipulate the actual values that are saved in the variable.
The value of the reference type is the object that is saved in memory. Unlike other languages, JS does not allow direct access to the location in memory, which means that the object's memory space cannot be manipulated directly. When you copy a variable that saves this object, the action is a reference to the object. However, when you add attributes to an object, the actual object is manipulated.
For example:

var person = new Object ();
var Zhangsan = person;//Action is a reference to an object actually Zhangsan is a pointer to the same object as the person.
person.name= "Lisi";//operation is the actual object.

Determine which value is that basic type you can use the TypeOf operator, and determine what type of reference you can use instanceof operator.
For example:

var person = new Object ();
var n = null;

Alert (typeof person);//object
alert (typeof N);//object

//object and Null typeof are both object

alert (person Instanceof object);//true
alert (n instanceof object);//False

//When detecting a reference type value and Object constructor, The instanceof operator always returns true, and if the value of the base type is detected using the instanceof operator, this operator will always return false because the base type is not an object.
ii. type of Object 1.Object Type

(1) object creation (two ways)
I.

    var person = new Object ();

Ii. using object literal notation

var person = {
    Name: "Zhangsan";
    Age:27
};
The last property is followed by a comma, which causes an error//property name in IE7 and earlier versions of opera and
can also use the string
var person = {
    "name": "Zhangsan",
    "age": 27
};

is blank in curly braces, you can define an object that contains only the default properties and methods,
var person={};//is equivalent to new object ();

Generally prefer to use the second method, because it is more clear and more data encapsulation feeling. The object literal is often used for passing parameters.
For example:

function DisplayInfo (args) {
    var output= "";
    if (typeof Args.name = = "string")
        output + = "Name:" +args.name+ "\ n";
    if (typeof args.age = = "number")
        output + = "Age:" +args.age+ "\ n";
    alert (output);
}

DisplayInfo ({
    name: "Zhangsan").
    Age:27
});
Name:zhangsan
//age:27
displayinfo ({
    name:lisi
});
Name:lisi

(2) Access to object properties (2 methods)
I. Point notation (recommended)

alert (person.name);

Ii. square brackets Notation (if the property name is liable to cause a syntax error or if the property name uses a keyword or is a reserved word that is recommended for use)

Alert (person["name"]);
2.Array Type

Different points from other reasons:
I. Each item in the array can hold any type of data.
For example:

var person = new Array ();
Person[0] = 1;
PERSON[1] = "Zhangsan";
PERSON[2] = true;

Ii. the size of the array can be dynamically adjusted
For example:

var person = new Array (2);
Person[0] = 1;
PERSON[1] = 2;
PERSON[2] = 3;//does not complain.

(1) The creation of the array
I. Using the array constructor

var person = new Array ();

Set length
var person = new Array (5);

Set value
var person = new Array ("Zhangsan", "Lisi");

Ii. using array literal notation

var person = ["Zhangsan", "Lisi"];
var person = [];//Create an empty array
var person = [,,,,];//is not advisable in this way!!! Each item gets a undefined value.

(2) acquisition of array values
Obtain by Square bracket method

This is similar to C Java
Alert (person[0]);

(3) The wonderful usage of length in JS array
The length in the JS array is not read-only or writable.
So you can change the length of the array dynamically by length, add new items, and so on.
For example:

Reduce the length of the array
var values=[1,2,3,4];
Values.length = 3;
Alert (values[3]); Undefined was supposed to be 4.
Increase the length of the array
var values=[1,2,3,4];
Values.length = 5;
Add New Item
var values = [1,2,3,4];
Values[values.length] = 5;
Values[values.length] = 6;
The length of the array equals the last index +1
var values = [1,2,3,4];
VALUES[1000] = [5];
alert (values.length);//1001
3 Array Method

(1) Conversion method
i.ToString ()
Returns a string that is nicely delimited by concatenation of the strings of each value in the array.
Ii.valueof ()
Return array
Iii.tolocalstring ()
The values returned are based on the range, often the same as ToString and valueof.
Iv.join ()
Receives a parameter, which is a string delimiter

(2) Stack method
Push (): Inserts an element to the top of the stack
Pop (): Removing elements to the top of the stack

var values = new Array ();
var count = Values.push (1,2);
alert (count);//2

count = Values.push (3);
alert (count);//3

var item = Values.pop ();
alert (item);//3
alert (count);//2

(3) Queue method
Push (): Adds an item to the end of the array
Shift (): Moves the first item in the divisor group and returns the item

var values = new Array ();
var count = Values.push (1,2);
alert (count);//2

count = Values.push (3);
alert (count);//3

var item = Values.shift ();
alert (item);//1
alert (count);//2

Unshift (): Adds any items to the front of the array and returns the length of the new array.
You can simulate queues in the opposite direction. Adds an item to the front of the array, removing the item at the end of the array. (Some people here think it's a stack, but it's not.) The remove item is the last item that removes the current first array you added to the array. Look at the example!

var values = new Array ();
var count = Values.unshift (1,2);
alert (count); 2

count = Values.unshift (3);
alert (count);//3

var item = Values.pop ();
alert (item);//2
alert (count);//2

(4) Reordering methods
Reverse (): Reverses the order of the sorted array items.
Sort (); The essence is to invoke the ToString () Fangfa of each item, and then compare the resulting string. This makes it easy to make mistakes. For example, the following:

var values=[1,10,15,5,20];
Values.sort ();
alert (values); 1,10,15,20,5

Workaround:
Sort () allows a comparison function to be accepted as an argument.
For example:

Small to large
function compare (value1,value2) {
    if (value1 < value2)
        return-1;
    else if (value1 > value2) return
        1;
    else return
        0;
}

var values=[1,10,15,5,20];
Values.sort (compare);
alert (values);//1,5,10,15,20
//from large to small sort
function compare (value1,value2) {
    if (value1 > value2)
        return-1;
    else if (value1 < value2) return
        1;
    else return
        0;
}
A simpler way to sort the
function compare (value1,values) return
    value1-value2;

(5) Operation method
Concat (): Creates a new array based on all the items in the current array. Specifically, you create a copy of the current array, and then add the received parameter to the end of the replica ... (should be a bit of stitching means it ...)

var person = ["Zhangsan", "Lisi", "Wangwu"];
var Moreperson = Person.concat ("Lalala", ["Liyiyi", "cheng123"]);

alert (person);//zhangsan,lisi,wangwu
alert (moreperson);//zhangsan,lisi,wangwu,lalala,liyiyi,cheng123

Slice (): In the case of only one parameter, returns all items starting at the specified position from the argument to the end of the current array, and if there are two parameters, the method returns the item between the start and end positions, but does not include the ending item.

var person = ["Zhangsan", "Lisi", "Wangwu", "Lalala", "Liyiyi"];
var person1 = Person.slice (1);
var person2 = Person.slice (1,4);

alert (person1);//lisi,wangwu,lalala,liyiyi
alert (person2);//lisi,wangwu,lalala
//ps: If Slice () Method has a negative number in its parameters, the length of the array is added to determine the appropriate position.

Splice (): Inserts an item into the array
Delete: You can delete any number of items . You need to specify two parameters: the location of the first item to delete and the number of items to delete.

Splice (0,2);//delete the first two items in an array

Insert: You can insert any number of items to a specified location , requiring at least three parameters: starting position, 0 (number of items to delete), items to insert, shares to insert multiple items, you can pass in the fourth fifth or more

Splice (2,0, "Zhangsan", "Wangwu");
Insert "Zhangsan" from the second item, "Wangwu"

Replace: You can insert any number of items to a specified location, and delete as many items as you want, at least three parameters: starting position, number of items to delete, and any number of items to insert, the inserted item does not have to match the number of items deleted

Splice (2,1, "Zhangsan", "Wangwu");
Delete the second item and insert the ZHANGSAN,WANGWU

(6) Location method
IndexOf (): Finds the position of a particular item in an array from the beginning of the array
LastIndexOf (): Start looking forward from the end of the array.
If not found, return-1

var numbers = [1,2,3,4,5,4,3,2,1];
Alert (Numbers.indexof (4)); 3
Alert (Numbers.lastindexof (4))//5

alert (Numbers.indexof (4,4));    5
Alert (Numbers.lastindexof (4,4));//3

(7) Iterative method
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, returns TRUE if the function returns true for either item;

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;

var someresult = numbers.some (function (item,index,array) {return
    item > 2;
});
alert (Someresult); True can be

var filterresult = numbers.filter (function (item,index,array) {return
    item > 2;}) as long as one satisfies
;

alert (Filterresult);//[3,4,5,4,3]

var mapresult = Numbers.map (function (item,index,array) {
    return Item * 2;
});

alert (Mapresult); [2,4,6,8,10,8,6,4,2]

Numbers.foreach (function (item,index,array) {
    //perform some operations
});

(8) Merging method
Reduce (): All items in an iterated algebra group starting from the first item of an array
Reduceright (): All items of an iterated algebra group starting from the last item of an array

Both methods receive two parameters: a function called on each item and an initial value that is the base of the merge.
Functions passed to reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function is automatically passed to the next item as the first argument.

var values = [1,2,3,4,5];

var sum = values.reduce (function (prev,cur,index,array) {return
    prev + cur;
});
alert (sum);//15


var sum1 = values.reduceright (function (prev,cur,index,array) {return
    prev + cur;
});
alert (sum1);//15   5 + 4 + 3 + 2 + 1
4 Date Type

In JS, the date type uses the number of milliseconds since UTC (International coordinated Time) to start at midnight January 1, 1970 to save dates. You can save 100 000 000 years before or after January 1, 1970.

(1) Create Date Object

var date = new Date ();
Without passing the parameter, the current time
//received parameter is the number of milliseconds for the corresponding date.
So there are two ways to do this: Date.parse (), DATE.UTC () converts a date in a particular format to a millisecond 
//date.parse () is usually a locale-specific.
var date = new Date (Date.parse ("may 1,2017"));
Equivalent to
date = new Date ("May 1,2017");
If the passed-in string does not represent a date, it returns Nan. If the date is passed into the date constructor, the background also invokes Date.parse ();
DATE.UTC () also returns the number of milliseconds corresponding to the date, but unlike date.parse (), different parameters are used when the build is worthwhile. The DATE.UTC () parameters are the year, based on the 0 month (0 for January), the Day of the month (1 to 31), the number of hours (0 to 23), minutes, seconds, and milliseconds. Only the first two of these parameters are required. If you do not supply the number of days in the month, the default

is 1. var date = new Date (DATE.UTC (2017,2));/= March 1, 2017 0 o'clock
About the Date.now () method, returns the number of milliseconds to indicate the date and time when this method was invoked
var start = Date.now ();

DoSomething ();

var end = Date.now ();

var time = End-start;

This method is currently supported by ie9+,firefox3+,safari3+,opera10.5 and Chrome. In browsers that do not support it, using the + operator to get the timestamp of the date object will also achieve the same effect

var start = +new Date ();

DoSomething ();

var end = +new Date ();

var tiem = End-start;

About ToString () and tolocalstring () and valueof () methods
The Tolocalstring () method returns the date and time in a format appropriate to the browser settings, which means that the AM,PM is included but does not contain time zone information, and the ToString () method typically returns a date and time with time zone information. Where time is generally expressed in military time.

ValueOf () returns the millisecond of the date. Therefore, it is convenient to use the label operator to compare dates.

var date1 = new Date (2017,0,1);
var date2 = new Date (2017,1,1);
Alert (Date1 < DATE2); True
alert (Date1 > Date2);//false
5 RegExp Type
var expression =/pattern/flags;

Include regular expressions and one or more flags.

About the flag regular expression matching pattern supports the following 3 flags:

G: Represents the global mode, where the pattern is applied to all strings, not immediately when the first occurrence is found.
I: Indicates case-insensitive
m: multiple-line mode, that is, when the end of a line of text continues to find the item in the next row that is in pattern matching.

Regular expression literal and constructor:

var reg =/\[bc\]at/;
Equivalent to (using a constructor)
//Because the schema parameter of the constructor is a string, in some cases the character is to be double escaped with the
var reg = new RegExp ("\\[bc\\]at");

The regular expressions constructed by the two are not the same, and regular expression literals always share the same regexp instance, and each new RegExp instance created using the constructor is a new instance.
For example:

var re = null,i;
Only one RegExp instance was created for/cat/.
Because the instance property is not reset, calling the test () method again in the loop fails. Because the first call to test () finds "cat", but the second call starts with a character indexed to 3, so it cannot be found.
for (i = 0; i < i++) {
    re =/cat/g;
    Re.test ("catastrophe");
}
A regular expression is created in each loop because each iteration creates a new REGEXP instance, so each call to test () returns true for
(i = 0; i < i++) {
    re = new RegExp ("Cat", "G ");
    Re.test ("catastrophe");
}

RegExp Instance Properties:
Global: Boolean value that indicates whether the G flag is set
IgnoreCase: Boolean. Indicates if I flag is set
Lastindex: An integer that represents the character position at which to begin searching for the next occurrence, starting with 0.
Multiline: Boolean value that indicates whether the M flag is set.
Source: The string representation of the regular expression, which is returned in literal form rather than in the string pattern in the incoming constructor.
For example:

var pattern1 =/\[bc\]at/i;

alert (pattern1.global);//false
alert (pattern1.ignorecase);//true
alert (pattern1.multiline);//false
alert (pattern1.lastindex);//0
alert (pattern1.source);//"\[bc\]at"

var pattern2 = new RegExp ("\\[bc\\]" At "," I ");
alert (pattern2.global);//false
alert (pattern2.ignorecase);//true
alert (pattern2.multiline);//false
alert (pattern2.lastindex);//0
alert (pattern2.source);//"\[bc\]at"

Example method for regexp:
(1) Exec (), this method is designed specifically for capturing groups. EXEC () receives a parameter, the string to which the pattern is applied, and then returns an array that contains the first occurrence information, or null if no match is encountered. The returned array is an instance of array, But contains two additional attributes:index and input.
Index: represents the position of the match in the string.
Input: represents a string that applies a regular expression.

var text = "Mom and dad and baby";
var pattern =/mom (and dad (and baby)?)? /gi;
The first item in the array is the entire string that matches, the second contains content that matches the first capturing group, the third contains content that matches the second capturing group, and so on.
var matchs = pattern.exec (text);
alert (matchs.index);//0
alert (matchs.input);/"Mom and Dad and Baby"
alert (matchs[0);/"Mom and Dad and baby"
alert (matchs[1]);/"and Dad and Baby"
alert (matchs[2);/"and Baby"
var text = "Cat,bat,sat,fat";
var pattern1 =/.at/;
Non-global mode returns the first occurrence of "cat" each time the exec () is invoked.
var matchs = pattern1.exec (text);
alert (matchs.index);//0
alert (matchs[0]);//cat
alert (pattern1.lastindex);//0

matchs = Pattern1.exec (text);
alert (matchs.index);//0
alert (matchs[0]);//cat
alert (pattern1.lastindex);//0
//Global mode, will continue to find new matches in the string
var pattern2 =/.at/g;
var matchs = pattern2.exec (text);
alert (matchs.index);//0
alert (matchs[

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.