JavaScript Native Object Master

Source: Internet
Author: User
Tags square root static class string format uppercase letter truncated javascript array

One. JavaScript Array class

Create a JS array in two different ways:

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

() can specify the length, or can not be specified, refers to the non-specified is irrelevant, because the length of the array in JS is variable

1.concat (ARR1,ARR2,ARR3......ARRX):

JS array Merge, return the merged new array, pass one or more arrays, the string can be line, return is a new merged array (the passed array will first turn into a string and then one after the incoming).

2. Join ():

  The array element is stitched into a string by the specified delimiter, and the default delimiter is a comma;

  var str=arr.join ("connector");

Fixed routines:
1. The character array is stitched as a word:
var word=chars.join ("");
Emphasis: 1. Join () ==>string (arr)
2. Seamless stitching must be added ""
2. Stitch the words into English sentences:
var stmt=words.join ("");
3. Stitch the array into a page element:

One of the values is that there are 2 ways to convert an array to a string, one is a string (arr), and the other is to use Arr.join ()

3. Slice (start,end): Intercept 

var subarr=arr.slice (starti,endi+1);
Copies the elements from the Starti position in arr to the Endi position, forming a new subarray. Emphasis: does not change the original array, only the new sub-array. Contains the head does not contain the tail!
Support for negative parameters: Arr.slice (-n,-m)
Intercept the last nth-beginning, to the end of the countdown to the first element. Arr.slice (ARR.LENGTH-N,ARR.LENGTH-M);
 

5, splice (): Delete Insert Substitution--Modify the original array directly

Delete: [Var deletes=]arr.splice (Starti,n)
Removing n elements after the start of the Starti position in ARR does not have to be considered with a header without a tail, in fact the deleted element will form a new array to return, and if the deleted element is also useful, the available variable catches the return value.
  Insert: arr.splice (starti,0, value 1, value 2,...)
The value 1, the value 2,... Insert into Arr starti position, the original Starti position and its value backward extrusion does not support array parameters: Cannot break the parameter array
  Replacement: [Var deletes=]
Arr.splice (Starti,n, value 1, value 2,...), deletes n elements after starti start in arr, and then in starti position, inserts a value of 1, the value 2. The number of elements removed and the number of new elements inserted can be unequal. JS automatically adjusts the capacity of the array.

4. Sort (fn):

Array sorting, by default the ASC code in alphabetical order, such as Apple row in front of orange, in fact, sort can also receive a parameter, the parameter function type, a bit similar to the meaning of the comparator 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, then B is in front of a

If the return value equals 0, the position A and B will not change

5. pop ():

Delete the last element of the array, subtract the length of the array by 1, and return the value of the element it deleted.

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

6. push (N1,n2,n3,.... NX):

Adds one or more elements to the end of the array and returns the length of the array after the addition,

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 parameter to pass

7. Reverse ():

Reverses the order of the elements in the array, that is, if the original array element is 1,2,3,4,5, after calling 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.

8. Shift ():

Deletes the first element of the array and returns the element 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

9. unshift (element1,....., Element):

Adds one or more elements to the beginning of the array and returns the added array length. At least one parameter must be passed.

Note that this method is directly manipulating the original array, adding the last element index=0, and so on.

Two. JS in the number class commonly used methods:

1. toFixed ():

  Rounds a number to a number that specifies the number of decimal digits, and the parameter value range is [0,20], which represents the number of decimal digits left after rounding,

If no parameters are passed in, the default parameter value equals 0

2. toprecision ():

Used to specify the number to a specified length, the method receives a parameter, the range of parameters is the [0,21] parameter represents the number of digits, if the total number of digits is greater than the value of the parameter and the number is a decimal, then rounding, if the total number of digits is less than the parameter value and the number is a decimal, So the number of decimal digits is automatically 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

3. isNaN (num):

This method is useful for judging whether it is a number.

Three. JS in the String class commonly used methods:

1, charAt (index):

The character used to return the specified position, and index is calculated starting at 0

2, charcodeat (index):

The ASCII code used to return the specified character

3, concat (element1,element2......elementx):

Used to stitch two or more strings

4, indexOf ():

Used to return the index of the first occurrence of the specified character in the string, starting with the first character and finding the immediate return. not finding the target will return-1.

5, lastIndexOf ():

Used to return the index of the first occurrence of the specified character in the string, but to start with the last character, without finding the target returns-1.

6, match ():

Used to retrieve a substring that matches a specified regular match, if global retrieval mode is turned on and there are multiple substrings that meet the criteria, then

The return is an array .

7, replace ():

  For a string substitution operation, receives two parameters.

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

Second argument: replace text, or it can be a function's return value

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

When using the function return value as the replacement text, there are two parameters in the function:

M indicates that the first argument in front is the substring of the regular match, and the second parameter is the index position of the substring in the original string.

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

If not found, returns-1

var " I like JavaScript. " ; alert (Str.search ("javascript"));

Explain the extension again

Replacement : Str=str.replace (Reg, "replacement value");
Replace the reg-matched keyword in str with the specified "replacement value"
  emphasis: reg post plus g, replace all
Do not add g, only replace the first one
Full version of Replace:
Str=str.replace (reg,function (kw) {
Processing logic;
Return "Replacement value";
})
Where KW automatically gets the current keyword each time it finds
function body, you can perform processing according to the current keyword, and finally return the corresponding replacement value

Derivative functions:
Delete keywords : str.replace (Reg, "");
Format: 2 steps:
1. Use grouping to split the original string according to the format.
For example: 19831226
(\d{4}) (\d{2}) (\d{2})
1 2 3
emphasis: Each grouping is automatically given an ordinal when matched:
2. Use the Replace method to get the contents of each group, and then stitch the format, when replacing.
Str.replace (Reg, "$ $ days");
Where: $n automatically matches sub-strings of nth groupings

8, Slice (start,end):

Used to intercept a string within a specified range of Start,end and return, this method does not manipulate the original string object data, but instead creates a copy of the string to hold the truncated string data if End is not specified, it is directly from start until the end of the array, if start or end is a negative number, Represents starting from the back, for example, 1, indicating the first element from the last count, and so on. The Intercept interval range is [start,end], the front closed after the opening interval, and start must be less than end if an element is not found, an empty string is returned

9, substr ():

For string interception, the method receives two parameters, the first argument starts, the start index position is truncated, the index is calculated from 0, and if the value of this parameter is negative, it is calculated from the end of the string, such as 1 for the last character, 2 for the penultimate character, and so on. The second parameter, length, is an optional, if not specified parameter, that is truncated to the end of the string.

Note: This method is not recommended for use with the

var " I like javascript! " ; alert (str.substr (7,

substring ():

Used to intercept the string within the start and end index intervals, the interval range is [Start,end], and before closing note: The parameter start and end must be non-negative integers, such as start is negative, the default is to assign start to 0, such as end is a negative number, By default, end is assigned a value of 0 and the intercept interval is changed to [0,start]. If start is greater than end, then the position of the two parameter values is exchanged first, i.e. the interval is changed to [End,start]

var " I like javascript! " :  alert (str1.substring (7));   var " I like javascript! " ;  Alert (str2.substring (3,-3

Note that 8,9,10 these 3 APIs are a function only the parameter meaning is different, the most used is slice (start,end), now substr () basic no one use, substring () see Personal habits use

One, tolowercase ():

Converts a string to lowercase

touppercase ():

Convert a string to uppercase

Split ("separator"): Cut 

var subs=str.split ("delimiter")
Str.split (REG)
  return value: an array containing all substrings after the cut, in the returned array, no longer contains delimiters.
  when to use: in the future, whenever a string is processed in a fragment, it is cut first, then each string is processed in segments
At last, we'll stitch together.
Fixed routines:
1. Break the string into a character array:
var chars=str.split ("");
2. Break the English sentence into words:
var words=stmt.split ("");
3. Cut the content of the page element into a sub-array ( This is how the string becomes an array )

There is a discovery that there are 2 APIs in the string and array that can be used for both types, concat () and slice (), in essence this 2API is the API in the array, why the string can be used, is that the 2 methods do not change the value of the original array, This attribute conforms to the character of the string (a read-only character, which does not change with the API's original string value).

four. common methods for date objects in JS:

getDate ():Returns the day of the one-month return value range: 1-31
GetDay ():Returns the day of the week that is the week, the return value range: 0-6,0 for Sunday, 6 for Saturday
getMonth ():Returns the number of months in a date, returning a range of values: 0-11,0 for January, 11 for December, this is a bit of a pervert.
getFullYear (): Returns the number of years in a date, expressed as a 4-digit number instead of a 2-digit abbreviated form
getHours ():Returns the number of hours, the return value range: 0-23
getminutes ():Returns the number of minutes: return value range: 0-59
getseconds ():Returns the number of seconds, return value range: 0-59
getmilliseconds ():Returns the number of milliseconds, the return value range: 0-999, this method name I do not understand, why seconds the first letter is not very written?
getTime ():Returns the number of milliseconds between the specified date from 00:00:00 January 1, 1970.
Parse (): Used to convert a qualifying date string to a date and returns the number of milliseconds from that date to 1970-01-01

Note: This method is a static method and should be called using the date class instead of being called with a Date object.
var date = Date.parse ("1987-06-05"); Firefox Ok,ie not ok

The parse method receives a date string format that is more compatible with the 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 a day in one months, value range: 1-31
setday ():Set the day of the week, that is, the days of the week, the value range: 0-6,0 for Sunday, 6 for Saturday
setmonth ():Set the month number in the date, value range: 0-11,0 for January, 11 for December, this is a bit of a pervert.
setfullyear ():Sets the number of years in a date, expressed as a 4-digit number instead of a 2-digit abbreviated form
sethours (): Set the number of hours, value range: 0-23
setminutes ():Setting the number of minutes: value range: 0-59
setseconds ():Set number of seconds, value range: 0-59
setmilliseconds ():Set the number of milliseconds, the value range: 0-999, this method named I do not understand, why the seconds first letter is not very written?
settime ():Sets the number of milliseconds between the specified date from 00:00:00 January 1, 1970.

toString ():Converts a Date object to a string, by default Greenwich Mean time format, GMT format
totimestring ():Converts the time portion of a Date object to a string form, GMT format
todatestring ():Converts the date part of a Date object to a string form, GMT format
tolocalestring:According to the local language of the date rules, the Chinese is yyyy years 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 to the first 3 parameters, which are optional, and the remaining parameters
Represents the year, month, day, hour, minute, second, and millisecond, respectively.
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 the GMT format by default, and for us, not applicable, we tend to want to display the YYYY-MM-DD hh:mm:ss format,
Date native object does not provide this function, it has to expand itself,

Five, JS in the Math class:

Note that this class is a static class and cannot be created by constructors, so the methods provided are static methods that are called directly from the class name and cannot be added to the new   

1, abs ():

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

Turns to a number, it returns Nan directly, and if so, returns its absolute value.

2, ceil ():

The incoming parameter is rounded up, and if it is not a number, an attempt is made to convert it to a number.

You cannot convert and you return Nan directly between

3, Floor ():

The incoming parameter is rounded down, and if it is not a number, an attempt is made to convert it digitally.

You cannot convert and you return Nan directly between

4, Max (X1,X2,X3.....XN):

  Returns the maximum value in the specified parameter, if one of the specified parameters cannot be converted to a number, directly

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

5, min (x1,x2,x3.....xn):

Returns the minimum value in the specified parameter, if one of the specified parameters cannot be converted to a number, directly

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

6, pow (x, y):

Returns the Y power of x, or Nan If the result of the calculation is negative, if the result is too large to cause a floating-point overflow,

Returns the positive infinity

7, random ():

Returns a random number between 0 and 1, containing 0 does not contain 1.

8, round (x):

The nearest integer to X. If x is a positive number, then 0.5 will turn to 1, and if it is-0.5, it will be dropped,

-0.50001 will turn into-1

9, sqrt (x):

Returns the square root of a number, or NaN if X is less than 0, and attempts to convert it if it is not a number.

You cannot convert and you return Nan directly between

Six, JS of the RegExp regular object:

Two ways to create regular objects:

1. Direct Volume: Var reg=/regular/ig;
When to use: only the regular is fixed and does not need to be generated dynamically, it is created with the direct amount
Taboo:/Is not allowed to contain "/" characters, if must be included, should be escaped to \/. such as/\d{6}/

2. Use the New keyword:
var reg=new RegExp ("regular", "IG");
When to use: whenever a regular expression needs to be dynamically generated, it is created with new.
Taboo: "" As long as contains \, "," to be escaped with \.

Detailed explanation

1. Regular expressions

What is: An expression that specifically specifies the regularity of characters in a string
When to use: Find replacement validation
How to use:
1. The simplest regular expression is the original text of the key word
2. Character set: A rule that specifies the list characters of a * character in a string.
How to use: [Alternate character list]
Special:
1. If the alternate character list contains characters for some Unicode exercises, use-omit the middle character:
For example: Match 1 capital letters: [A-z]
1 digits: [0-9]
1 lowercase letters: [A-z]
1-Letter: [A-za-z]
1-bit kanji: [\U4E00-\U9FA5]
2. indicates that except XXX is OK:
[^47] except 4 and 7.
3. Predefined character sets: simplification of common character sets
1 digits: \d ==>[0-9]
1-bit letters, numbers or _:
\w ==>[a-za-z0-9_]
1-bit null character: \s Space, tab, line break

1-bit arbitrary characters:. All characters except for line breaks
4. quantifiers: Rules that specifically specify the number of occurrences of a character set
How to use: After a character set, modify the number of occurrences of the previous adjacent character
There are definite numbers:
{n,m} at least n times, up to M times
{N,} at least n times, more than an unlimited
{n} must be n times, not more or less

Ambiguous quantity:
? Optional, up to 1 times
* Optional, more than the unlimited
+ at least 1 times, more than the unlimited
5. Select and group:
Select: Or | Two in two expressions select a match
Grouping: Marking multiple character sets with () as a group
When to use: when you want a quantifier to modify multiple character sets at the same time, you need to group multiple character sets first.
Phone Number:
+86 or 0086 optional, up to 1 times
Empty characters at least one, more than an unlimited
1
Pick a 3,4,5,7,8 among the
9-digit number
(\+86|0086)? \s+1[34578]\d{9}
6. Specify the matching location:
String start: ^ For example: empty character at the beginning
End of string: $ For example: empty character at the end
Fixed routines:
If you want to have a complete match from beginning to end, add ^ before and $--verify
Exception: ^\s+|\s+$ is not a complete match from beginning to end
Because | The priority level is the lowest, and the time is divided into
The boundary of a word: \b

Instance

Requirements: Password strength verification
A combination of 6~8 bits, letters, and numbers containing at least one uppercase letter and one digit
Pre-contract: Before the formal match, first browse the entire expression, whether it conforms to the specified rules
(? Rules $)
1. The pre-judgment is not entirely composed of letters:
Description: Contains at least one digit or special symbol
(?! [a-za-z]+$]
2. Pre-judgment is not entirely composed of numbers and lowercase letters
Description: Contains at least one uppercase letter or special symbol
(?! [a-z0-9]+$]
3. Must be a combination of 6~8 letters and digits
^(?! [a-za-z]+$) (?! [a-z0-9]+$] [a-za-z0-9]{6,8}$

Regular Expressions: 2 modes:
Greedy mode: The default regular expression matches the longest string that meets the criteria
Lazy mode: Let the regular expression match only the shortest substring of the qualifying string
Greed changes laziness: *->.*? +->.+?

  Validation API: Checks if a string is exactly the same as the regular expression.
How to verify: Var bool=reg.test (str);
Check if STR matches reg exactly, and return true if validation passes, otherwise false.
  emphasis: in the validation function, the regular expression must be followed by ^, plus $. If not added, as long as the partial match, is true. Do not add the G suffix because it matches only once.

JavaScript Native Object Master

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.