A summary of common methods for JavaScript native objects (recommended) _javascript tips

Source: Internet
Author: User
Tags closure getdate square root static class string format time interval javascript array

Here are my Learning notes about JavaScript written in the school tutorial, each of which I have personally tested, the purpose of each method and the list of parameters, I have added my own understanding after my own practice, the explanation is relatively detailed. are recorded for inspection:

JavaScript Array class:

Create JS arrays two ways:

var arr = []; Or
var arr = new Array ();

() can be specified in length, or can not be specified, it does not mean that it does not matter,

Because the length of the array in JS is variable

Concat (ARR1,ARR2,ARR3......ARRX): JS array Merge, return the merged new array, at least need to pass an array, or can pass multiple arrays

var arr1 = new Array (3);

arr1[0] = "George";

ARR1[1] = "John";

arr1[2] = "Thomas";

ARR1[3] = "Jeery";



var arr2 = new Array (3);

Arr2[0] = "James";

arr2[1] = "Adrew";

ARR2[2] = "Martin";



var arr3 = new Array (3);

Arr3[0] = "Java";

arr3[1] = "C #";

ARR3[2] = "PHP";



var arr4 = Arr1.concat (ARR2,ARR3);

alert (ARR4);

join (): The array element is returned as a string by the specified delimiter, and the default delimiter is an English comma

var arr = new Array (3)

arr[0] = "George";

ARR[1] = "John";

arr[2] = "Thomas";

ARR[3] = "Jeery";

arr.join (".");

Sort (FN): array ordering by default in ascending order of ASC code in English letters, such as Apple in front of orange, in fact

Sort can also receive a parameter, the function type, which is similar to the meaning of a comparer in Java,

That is, if you do not want to sort by default comparison rules, you must provide a comparison function that has two parameters a, B,

If the return value is less than 0, a is in front of b

If the return value is greater than 0, B is ranked ahead of a

If the return value is equal to 0, the position of A and B is unchanged

var arr = new Array (6);

arr[0] = 5;

ARR[1] = 23;

arr[2] = 4;

ARR[3] = 18;

arr[4] =;

ARR[5] = 10;

Arr.sort (sortnumber);



function Sortnumber (A, B)

{return

a-b

}

pop (): deletes the last element of the array, reducing the length of the array by 1 and returning the value of the element it deletes.

If the array is already empty, the pop () does not change the array and returns the undefined value.

var arr = new Array (6);

arr[0] = 5;

ARR[1] = 23;

arr[2] = 4;

ARR[3] = 18;

arr[4] =;

ARR[5] = 10;



var a = Arr.pop ();

alert (a); For

(var x in arr) {

alert (arr[x]);

}

Push (N1,n2,n3,.... NX): Adds one or more elements to the end of the array and returns the length of the added array.

Note that this method operates on the original array object and does not create a copy. This method can receive multiple parameters,

At least one argument to pass

var arr = new Array (6);

arr[0] = 5;

ARR[1] = 23;

arr[2] = 4;

ARR[3] = 18;

arr[4] =;

ARR[5] = 10;



var len = Arr.push (44,80);

alert (len); For

(var x in arr) {

alert (arr[x]);

}

reverse (): reverses the order of elements in an array, that is, if the original array element is 1,2,3,4,5, after the call to reverse (),

Element order is 5,4,3,2,1, note that this method directly operates on the original array object and does not create a copy.

var arr = [3,5,11,6,90,0];

arr.reverse ();

for (var x in arr) {

alert (arr[x]);

}

shift (): deletes the first element of the array and returns the element that it deletes

If the array is already empty, shift () does not change the array and returns the undefined value

Note that this method directly operates on the original array and does not create a replica object

var arr = [3,5,11,6,90,0];

var a = Arr.shift ();

alert (a); For

(var x in arr) {

alert (arr[x]);

}

Slice (start,end): used to intercept the array element between start and end and return to the new array
Note that this method does not modify the original array and creates an array replica object.

If end is not specified, it means that it is directly from start to the ends of the array.

If start or end is a negative number, it starts at the back, such as

-1, which means that from the penultimate element, and so on.

The interval range of the interception is [Start,end], the opening interval after the front closure, and the start must be less than end

If an element is not found, an empty array is returned-the length of the array is 0

var arr = [3,5,11,6,90,0];

var a = Arr.slice (2,4);

Alert (A.join ());

Splice (index,howmany,element1,....., elementx):

Used to delete 0 or more elements starting at index, and one or more of the arguments declared in the argument list

Multiple values to replace the deleted elements and return a new array of elements that have just been deleted.

Note: This method is a direct manipulation of the original array object and does not create a copy of the object

First parameter: Indicates start deletion from index position, index starts from zero calculation

Second parameter: Indicates that the first two parameters are required, and the following parameters are optional, starting at the index position and continuously deleting several elements.

The following argument is added with the element that is added, starting at index, if the number of elements added later is greater than

Actually delete the number of elements, a few more, the following elements will move back several. For example, you actually delete 4 elements,

In fact, you add 6 elements, which will eventually add 6 elements from index, because only 4 elements are deleted before

Position is not enough, so the elements behind will automatically move back 2 digits.

var arr = [3,5,11,6,90,0,15,57,70,20];

var a = Arr.splice (0,4,1,2,3,4,5,6);

alert (a); For

(var x in arr) {

alert (arr[x]);

}

Unshift (element1,....., Element):

Adds one or more elements to the beginning of the array and returns the length of the array after the addition. At least one argument must be passed.

Note that this method is the direct manipulation of the original array, the last element added index=0, and so on.

var arr = [3,5,11,6,90,0,15,57,70,20];

Arr.unshift (22,23,24);

Alert (arr.tostring ());

alert (arr.length);



function to extend array:

Array.prototype.indexOf = function (o) {for

(var i = 0,len=this.length i<len;i++) {

if (this[i] = O) {

ret Urn i; 

} 

} 

return-1;

}

Array.prototype.remove = function (o) {

var index = this.indexof (o);

if (index!=-1) {

this.splice (index,1);

}

return this;

} 

var arr = [3,5,11,6,90,0,15,57,70,20];

Arr.remove (m);

Alert (arr.tostring ());

alert (arr.length);

JS in the number class commonly used methods:

toFixed (): rounds a number to a number with a specified number of decimal places, with a value range of [0,20], indicating the number of decimal places to keep after rounding,
If no arguments are passed in, the default parameter value equals 0

var num = 12.5563;

alert (num.tofixed ());

Alert (num.tofixed (2));

toprecision (): used to pinpoint a number to a specified length by receiving a parameter with a parameter range of [0,21]

Parameter represents the number of digits, if the total number of digits is greater than the parameter value and the number is a decimal, then the

Rounding, if the total number of digits is less than the value of the parameter and the number is a decimal, then the number of decimal places will automatically fill 0

If the total number of digits is less than the parameter value and the number is an integer, then the scientific notation is used instead.

var num1 = 100009;

var num2 = m;

var num3 = 11111111.00009;

var num4 = 1.00609;

Alert (Num1.toprecision (5));

Alert (Num2.toprecision (5));

Alert (Num3.toprecision (15));

Alert (Num4.toprecision (3));

isNaN (num): This method is useful for determining whether it is a number

Common methods for string in JS:

CharAt (Index): the character used to return the specified position, which is calculated starting at 0

charCodeAt (Index): ASCII code used to return a specified character

Concat (ELEMENT1,ELEMENT2......ELEMENTX): For stitching two or more strings

IndexOf (): Returns the index for the first occurrence of the specified character in the string, starting with the first character and finding the return immediately.

LastIndexOf (): Returns the index for the first occurrence of the specified character in the string, but begins the search from the last character.

Match (): Retrieves a substring that matches a specified regular match, if the global retrieval mode is turned on and there are multiple strings that match the criteria, then

Returns an array.

var str = "Hello world! How are? What are you doing? ";

var arr = Str.match (/you/g);

alert (arr);

var str= "1 plus 2 equal 3"

alert (Str.match (/\d\s/g));



replace (): used for string substitution operations, receiving two parameters.

First argument: Represents a string to be replaced, or a replacement regular expression

Second argument: alternate text, or return value of a function

Note that this method does not change the original string object, but instead returns the new string object.

var str = "I like Java,java are so easy to learning!" Let ' s together for Java;

var test = str.replace (/java/g, "Javascript");

alert (str);

alert (test);



var name = "Doe, John"; 

alert (Name.replace (\w+) \s*, \s* (\w+)/, "$ | $));



var name = "I like Java,java are so easy!";

var test = Name.replace (/java/g, function (m,i) {alert (m); alert (i); return "JavaScript";});

alert (test);

When you use function return values as alternate text, there are two parameters in the function:

M indicates that the first argument is a substring that is matched to, and the second argument is the index position of the substring in the original string

Search (): The index that returns the first occurrence of a specified substring or substring that matches a specified regular expression in the original string.

If not found, return-1

var str = "I like JavaScript."
Alert (Str.search ("JavaScript"));

Slice (start,end): Used to intercept a string within a start,end specified interval and return it,

Instead of manipulating the original string object data, this method creates a copy of the string to save the intercepted string data

If end is not specified, it means that it is directly from start to the ends of the array.

If start or end is a negative number, it starts at the back, such as

-1, which means that from the penultimate element, and so on.

The interval range of the interception is [Start,end], the opening interval after the front closure, and the start must be less than end

If an element is not found, an empty string is returned

var str = "Hello world!";

var test = Str.slice ( -2,-1);

alert (test);

alert (str);

Split (): Splits the original string with the specified split character or matching character of the regular expression, and returns the result as an array.

This method can also receive the second argument, and the second parameter can limit the maximum number of array elements that are eventually returned.

var str= "How are your doing today?"

Alert (Str.split (/\s/));

SUBSTR (): For string interception, method receives two parameters,

The first parameter, start, indicates that the index starts at 0, and if the value of this parameter is negative,

is calculated from the end of the string, for example-1 for the last character, 2 for the penultimate character, and so on.

The second parameter length, which indicates the length of the intercepted string, which is optional, if this parameter is not specified,

Is truncated to the end of the string by default.

Note: This method has not recommended using the

var str = "I like javascript!";
Alert (STR.SUBSTR (7,10));

SUBSTRING (): Used to intercept the string within the start and end index intervals, with an interval range of [start,end], open before closing

Note: The parameter start and end must be non-negative integers.

If start is a negative number, the start assignment is set to 0 by default.

If the end is a negative number, it is assigned a value of 0 and the intercept interval is replaced by [0,start).

If start is greater than end, the position of two parameter values is exchanged first, that is, the interval is changed to [End,start)

var str1 = "I like javascript!":

alert (str1.substring (7,18));

var str2 = "I like javascript!";

alert (str2.substring (3,-3));



toLowerCase (): Convert string to lowercase

toUpperCase (): Converting strings to uppercase





Common methods for Date objects in JS:
Date (): This method is the constructor of the date class, which receives a date format string.
The default is to take the system current time if the constructor is not passed the parameter
The constructor can receive a number of milliseconds from 1970-01-01 to construct the date object.
You can also receive a specified format date string to build a Date object
var date = new Date ("06 05,1987"); Firefox OK ie not ok
var date = new Date ("6 5,1987"); Firefox OK ie not ok
var date = new Date ("06 05,1987 23:12:33"); Firefox OK ie not ok
var date = new Date ("6 5,1987 23:12:33"); Firefox OK ie not ok
var date = new Date ("1987,06 05"); Firefox OK ie not ok
var date = new Date ("1987,6 5"); Firefox OK ie not ok
var date = new Date ("1987,06,05"); Firefox OK ie not ok
var date = new Date ("1987,6,5"); Firefox OK ie not ok
var date = new Date ("1987,06 05,23:12:33"); Firefox OK ie not ok
var date = new Date ("1987,6 5,23:12:33"); Firefox OK ie not ok
var date = new Date ("1987,06,05,23:12:33"); Firefox OK ie not ok
var date = new Date ("1987,6,5,23:12:33"); Firefox OK ie not ok
var date = new Date ("1987/6/5,23:12:33"); Firefox and IE are OK
var date = new Date ("1987/06/05,23:12:33"); Firefox and IE are OK
var date = new Date ("06/05/1987,23:12:33"); Firefox and IE are OK
var date = new Date ("6/5/1987,23:12:33"); Firefox and IE are OK
var date = new Date ("1987/6/5"); Firefox and IE are OK
var date = new Date ("1987/06/05"); Firefox and IE are OK
var date = new Date ("06/05/1987"); Firefox and IE are OK
var date = new Date ("6/5/1987"); Firefox and IE are OK
var date = new Date ("06-05-1987"); IE OK, Firefox not ok
var date = new Date ("6-5-1987"); IE OK, Firefox not ok
var date = new Date ("1987-06-05"); Firefox Ok,ie not ok
alert (date);
These examples are sufficient to illustrate that if the date () constructor needs to receive a date format string,
The string format should be given as follows:
Yyyy/m/d
Yyyy/mm/d
YYYY/M/D HH:mm:ss
YYYY/MM/D HH:mm:ss
M/d/yyyy
Mm/dd/yyyy
M/D/YYYY HH:mm:ss
MM/DD/YYYY HH:mm:ss

GetDate (): Returns one day of one months, return value range: 1-31
Getday (): Returns the day of the week, which is the week, returns the range of values: 0-6,0 says Sunday, 6 means Saturday
GetMonth (): Returns the number of months in the date, returning the range of values: 0-11,0 January, 11 for December, this is a little perverted.
getFullYear (): Returns the number of years in a date, abbreviated as a 4-digit number instead of a 2-digit number
GetHours (): Back to hours, return range of values: 0-23
Getminutes (): Back minutes: Return value range: 0-59
Getseconds (): Returns the number of seconds, return value range: 0-59
Getmilliseconds (): Returns the number of milliseconds, returns the range of values: 0-999, this method name I mean I can't understand why the seconds first letter is not very written.
GetTime (): Returns the number of milliseconds between the specified date from January 1, 1970 00:00:00.
Parse (): Used to convert a date string that matches the specified date to the day and return the number of milliseconds from that date to 1970-01-01

Note: This method is a static method and should not be invoked with the date object, but should be invoked using the date class.
var date = Date.parse ("1987-06-05"); Firefox Ok,ie not ok
var date = Date.parse ("06-05-1987"); IE OK, Firefox not ok
var date = Date.parse ("06/05/1987"); IE and Firefox are OK
var date = Date.parse ("1987/06/05"); IE and Firefox are OK
var date = Date.parse ("6/5/1987"); IE and Firefox are OK
var date = Date.parse ("1987/6/5"); IE and Firefox are OK
var date = Date.parse ("1987/06/05 23:12:22"); IE and Firefox are OK
var date = Date.parse ("6/5/1987 23:12:22"); IE and Firefox are OK
var date = Date.parse ("1987/6/5 23:12:22"); IE and Firefox are OK

alert (date);
With these examples, it is easy to see that the date string format received by the Parse method is more compatible in format:

Yyyy/mm/dd
yyyy/m/d
mm/dd/yyyy
m/d/yyyy
yyyy/mm/dd HH:mm:ss
yyyy/m/d HH:mm:ss
mm/dd/yyyy HH: Mm:ss
m/d/yyyy HH:mm:ss
 
setdate (): Set one day of one months, value range: 1-31
Setday (): Set the day of the week, the days of the week, the value range: 0-6, 0 for Sunday, 6 for Saturday
Setmonth (): Set the number of months in the date, value range: 0-11,0 for January, 11 for December, this is a bit of a pervert
setFullYear (): Set the number of years in the date, Abbreviated as a 4-digit number instead of a 2-digit
Sethours (): Set hours, values range: 0-23
setminutes (): Set minutes: Value range: 0-59
setseconds (): Set the number of seconds Value range: 0-59
setmilliseconds (): Set the number of milliseconds, the value range: 0-999, this method name I do not understand why the seconds first letter is not written?
SetTime (): Sets the number of milliseconds between the specified date from January 1, 1970 00:00:00.
 
ToString (): Converts a Date object to a string, by default the Greenwich Mean time format, GMT format
totimestring (): Converts the time portion of a Date object to a string, GMT format
toDateString (): Converts the date part of a dates object to a string, in GMT format
toLocaleString: According to the local language's date rule, the Chinese is yyyy mm month DD Day HH:MM:SS
DATE.UTC ( YEAR,MONTH,DAY,HOURS,MINUTES,SECONDS,MS):

This method is used to return the number of milliseconds from 1970-01-01 based on the universal. The first 3 parameters are required, the remaining parameters are optional, the
represents the year, month, day, hour, minute, second, millisecond,
the number of milliseconds returned by this method can be passed to the date () constructor,
            the ToString method of the
Date object is converted to GMT by default, and for us, it does not apply. We tend to want to appear as YYYY-MM-DD hh:mm:ss format,
Date native objects do not provide this functionality and have to expand on their own,

Date.prototype.format = function (format) {  var o = {  "M+"  :  This.getmonth () +1, //month  month   "d+"  : this.getdate (), //day  day   "h+"  

:  this.gethours (), //hour    "m+"  : this.getminutes (), //minute  min   "S+"  : this.getseconds (), //second  sec   "q+"  : math.floor ((This.getMonth () +3)/ 3),  //quarter quarter   "S"  : this.getmilliseconds ()  //millisecond milliseconds  }  if (/(y+)/. Test (format)  {  format = format.replace (regexp.$1,  (this.getfullyear () + ""). substr (4  - regexp.$1.length)); }  for (Var k in o)  {  if (New regexp ("() + k + ")"). Test (format))  {  Format = format.replace (regexp.$1, regexp.$1. length==1 ? o[k] :  ("+ o[k]"). substr (("" + o[k). Length); }&nbsp



 }  return format; } 

Use examples:

var date = new Date ();

Alert (Date.format ("Yyyy-mm-dd hh:mm:ss"));

JS's native date class also does not provide an Add method that adds or subtracts a specified number of days from the original date base, which is now expanded as follows:

DATE.PROTOTYPE.DATEADD = function (interval,number)

{

var d = this;

var k={' y ': ' fullyear ', ' Q ': ' Month ', ' m ': ' Month ', ' W ': ' Date ', ' d ': ' Date ', ' H ': ' Hours ', ' n ': ' Minutes ', ' s ': ' Seconds ', ' Ms ': ' milliseconds '};

var n={' Q ': 3, ' W ': 7};

Eval (' D.set ' +k[interval]+ ' (D.get ' +k[interval]+ ' () + ' + ' + (n[interval]| | 1) (*number) + ') '); return

D;

}



Interval parameter:
y       year
q       quarter
m        month
d       Day
w        Week
h       hours
n       minutes
s        sec
ms      millisecond
 
Number parameter: time interval, must be numeric, is a positive number to get the future date of the specified interval, a negative number for the past date
 
//To calculate the time interval between two dates,
//Use this method to compare the size of two dates, if the return value is greater than 0, to indicate a large objDate2,
If less than 0, it means that the objDate2 is relatively small

Date.prototype.dateDiff = function (interval,objdate2)
{
 var d=this, i={}, T=d.gettime (), T2=objdate2.gettime ();
 i[' y ']=objdate2.getfullyear ()-d.getfullyear ();
 i[' q ']=i[' y ']*4+math.floor (Objdate2.getmonth ()/4)-math.floor (D.getmonth ()/4);
 i[' m ']=i[' y ']*12+objdate2.getmonth ()-d.getmonth ();
 i[' Ms ']=objdate2.gettime ()-d.gettime ();
 i[' W ']=math.floor ((t2+345600000)/(604800000))-math.floor ((t+345600000)/(604800000));
 i[' d ']=math.floor (t2/86400000)-math.floor (t/86400000);
 i[' h ']=math.floor (t2/3600000)-math.floor (t/3600000);
 i[' n ']=math.floor (t2/60000)-math.floor (t/60000);
 i[' s ']=math.floor (t2/1000)-math.floor (t/1000);
 return i[interval];
}

Interval parameter: Refer to the interval parameter description of the above DateAdd method,

ObjDate2: Another Date object

The math class in JS:

This class is a static class and cannot be created by constructors, so the method provided is static and is invoked directly through the class name

ABS (): Gets the absolute value of a number, and if the supplied argument is a string, it first attempts to convert it to a number, if it cannot

When converted to a number, it returns directly to Nan and returns its absolute value if it can.

Ceil (): The incoming argument is rounded up, and if the incoming is not a number, an attempt is made to convert it digitally.

If you cannot convert, you return directly to Nan

Floor (): An incoming parameter is rounded down, and if the incoming is not a number, an attempt is made to convert it digitally.

If you cannot convert, you return directly to Nan

Max (X1,X2,X3.....XN): Returns the maximum value in the specified parameter, if one of the specified arguments cannot be converted to a number, directly

Returns Nan, which returns a negative infinity if no arguments are passed in

Min (X1,X2,X3.....XN): Returns the minimum value in the specified parameter, if one of the specified arguments cannot be converted to a number, directly

Returns Nan, or returns a positive infinity if no arguments are passed in

Pow (x,y): Returns the Y-power of X, if the result is negative, returns Nan if the result of the calculation is too large to cause a floating-point overflow,

Returns the positive infinity

Random (): Returns a random number between 0 ~ 1.

Round (x): The nearest integer to X. If x is a positive number, then 0.5 will turn into 1, and if it is-0.5, then it will drop,

-0.50001 will turn into 1.

sqrt (x): Returns the square root of a number, or NaN if X is less than 0,

If the incoming is not a number, an attempt is made to convert it digitally.

If you cannot convert, you return directly to Nan

JS regexp Regular object:

Two ways to create regular objects:

1./pattern/attributes

pattern is the regular expression part,

Attributes: Optional parameters, including attributes "G", "I" and "M" values

G: Represents a global match (finds all matches rather than stops after the first match is found)

I: Indicates that the case is ignored

M: multiple-line matching

2,new RegExp (pattern,attributes), second parameter optional

Above this JavaScript native object commonly used method summary (recommendation) is small series share to everybody's content, hope can give everybody a reference, also hope everybody support cloud-dwelling community a lot.

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.