Detailed JavaScript's built-in objects _javascript tips

Source: Internet
Author: User
Tags array length arrays numeric value set time

What is an object

Everything in JavaScript is an object, such as a string, a numeric value, an array, a function, and so on, with attributes and methods for each object.

object's properties : reflect some of the object's specific properties, such as: the length of the string, image length and so on;

Object : An action that can be performed on an object. For example, the form of "submit" (submit), the time of "get" (getyear), etc.;

JavaScript provides a number of built-in objects, such as String, Date, array, and so on, defined before using an object, such as using an array object:

var objectname =new Array ();//Use the New keyword to define an object

Or

var objectName =[];

To access the syntax of an object property:

objectName.propertyName

If you use the Length property of the array object to get the size of the array:

var myarray=new array (6);//define Array object
var myl=myarray.length;//access Array Length property

After the above code executes, the MYL value will be: 6

Ways to Access Objects:

objectName.methodName()

Use the toUpperCase () method of the String object to convert text to uppercase:

var mystr= "Hello world!"; /Create a String
var request=mystr.touppercase ();//Use String object method

After the above code executes, the value of the request is: HELLO world!

Date Date Object

Date objects can store any one date, and can be accurate to milliseconds (1/1000 seconds).

Define a Time object:

var Udate=new Date();

Note: The first letter using the keyword new,date () must be capitalized.

Make Udate a Date object and already has an initial value: Current time (current computer system time).

If you want to customize the initial values, you can use the following methods:

var d = new Date (2012, 10, 1); October 1, 2012
var d = new Date (' OCT 1, 2012 ');//October 1, 2012

We'd better use the "methods" described below to strictly define the time.

Access method Syntax: "< date objects >.< methods >"

Common methods for processing time and dates in a Date object:

Returns/sets the Year method

Get/setfullyear () Returns/sets the year, which is represented by a four-digit number.

var mydate=new Date ()//Current Time March 6, 2014
document.write (mydate+ "<br>");//output Current time
document.write ( Mydate.getfullyear () + "<br>"),//output current year
mydate.setfullyear (81);//Set Year
document.write (mydate+ "< Br> "); The output year is set to 0081 years.

Note: Different browsers, Mydate.setfullyear (81) results are different, the year is set to 0081 or 812 of cases.

Results:

Thu Mar 2014 10:57:47 gmt+0800
2014
Thu Mar 0081 10:57:47 gmt+0800

Attention:

    • The resulting formats are: week, month, day, year, time, minute, second, time zone. (Firefox browser)
    • Different browsers, the time format has differences.

Return Week method

Getday () Returns the week, returns a number of 0-6, and 0 indicates Sunday. If you want to return the corresponding "week", complete with the array, the code is as follows:

<script type= "Text/javascript" >
 var mydate=new date ();//define Dates object
 var weekday=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Defines the array object, assigns the value Var mynum=mydate.getday () to each array item,
 or the return value is stored in the variable mynum
 document.write (Mydate.getday ());//Output Getday () Get the value
 document.write ("Today is:" + weekday[mynum]);//Output Week
</script>

Note: The above code was run on March 2, 2016, Wednesday.

Results:

3
today are: Wednesday

return/Set Time method

Get/settime () Returns/sets the time, in units of milliseconds, that calculates the number of milliseconds from January 1, 1970 0 o'clock to the date that the Date object refers to.

If you postpone the current date object by 1 hours, the code is as follows:

<script type= "Text/javascript" >
 var mydate=new Date ();
 document.write ("Current Time:" +mydate+ "<br>");
 Mydate.settime (Mydate.gettime () + * * 1000);
 document.write ("Defer One Hour time:" + mydate);
</script>

Results:

Current time: Thu Mar 6 11:46:27 utc+0800 2014

Postponed one hour: Thu 6 12:46:27 utc+0800 2014

Attention:

    • One hour, 60 minutes, 60 seconds, 1000 milliseconds per second.
    • The delay of 1 hours is: "X.settime (X.gettime () + 60 60 1000);"

String String Object

The way to define a string is to assign a value directly. Like what:

var mystr = "I love JavaScript!"

After defining the MYSTR string, we can access its properties and methods.

To access the property length of a String object:

Stringobject.length; Returns the length of the string.

var mystr= "Hello world!";
var myl=mystr.length;

After the above code executes, the MYL value will be: 12

Ways to access String objects:

Use the toUpperCase () method of the string object to convert the lowercase letter of the string to uppercase:

var mystr= "Hello world!";
var mynum=mystr.touppercase ();

After the above code executes, the Mynum value is: HELLO world!

Returns the character at the specified position

The CharAt () method returns the character at the specified position. The character returned is a string of length 1.

Grammar:

stringObject.charAt(index)

Parameter description:

Attention:

1. The subscript for the first character in the string is 0. The last character's subscript is the string length minus one (string.length-1).

2. If the parameter index is not between 0 and String.length-1, the method returns an empty string.

For example: In the string "I love javascript!", return the character of position 2:

<script type= "Text/javascript" >
 var mystr= "I Love javascript!"
 document.write (Mystr.charat (2));
</script>

Note: A space is also counted as a character.

Running results of the above code:

l

Returns the position of the specified string for the first occurrence

The IndexOf () method returns the location of the first occurrence of a specified string value in a string.

Grammar

stringObject.indexOf(substring, startpos)

Parameter description:

Description

1. This method retrieves the string stringobject from beginning to end to see if it contains substring substring.

2. Optional parameters, starting from the startpos position of Stringobject to find substring, if no this parameter will be found from the beginning of Stringobject.

3. If a substring is found, it returns the position of the first occurrence of substring. The character position in the Stringobject is starting at 0.

Attention:

The 1.indexOf () method is case-sensitive.

2. If the string value to retrieve does not appear, the method returns-1.

For example: a different search within the "I Love javascript!" string:

<script type= "Text/javascript" >
 var str= "I Love javascript!"
 document.write (Str.indexof ("I") + "<br/>");
 document.write (Str.indexof ("V") + "<br/>");
 document.write (Str.indexof ("V", 8));
</script>

The output of the above code:

0
4
9

String Split Split ()

Knowledge Explanation:

The split () method splits the string into an array of strings and returns this array.

Grammar:

stringObject.split(separator,limit)

Parameter description:

Note: If an empty string ("") is used as a separator, then each character in the Stringobject will be split.

We'll split the string in different ways:

Splits the string with the specified symbol, as follows:

var mystr = "www.baidu.com";
document.write (Mystr.split (".") + "<br>");
document.write (Mystr.split (".", 2) + "<br>");

Run Result:

Www,baidu,com
Www,baidu

Split the string into characters, as follows:

document.write (Mystr.split ("") + "<br>");
document.write (Mystr.split ("", 5));

Run Result:

W,w,w,., b,a,i,d,u,., c,o,m
w,w,w,., b

Extract string substring ()

The substring () method extracts characters from a string mediation between two specified subscripts.

Grammar:

stringObject.substring(starPos,stopPos)

Parameter description:

Attention:

The returned content is all characters starting at start (the character that contains the start position) to the stop-1, and the length is stop minus start.

If the argument start is equal to the stop, the method returns an empty string (that is, a length of 0).

If start is larger than stop, the method swaps the two parameters before extracting the substring.

Using substring () to extract the string from the string, the code is as follows:

<script type= "Text/javascript" >
 var mystr= "I love JavaScript";
 document.write (mystr.substring (7));
 document.write (mystr.substring (2,6));
</script>

Run Result:

JavaScript Love

Extracts a specified number of characters substr ()

The substr () method extracts a specified number of strings from the string, starting at the startpos position.

Grammar:

stringObject.substr(startPos,length)

Parameter description:

Note: If the parameter startpos is a negative number, position from the tail of the string. In other words,-1 refers to the last character in the string, 2 to the penultimate character, and so on.

If the startpos is negative and the absolute value is greater than the string length, Startpos is 0.

Using substr () to extract some characters from the string, the code is as follows:

<script type= "Text/javascript" >
 var mystr= "I love javascript!";
 document.write (MYSTR.SUBSTR (7));
 document.write (Mystr.substr (2,4));
</script>

Run Result:

javascript!
Love

Math Object

The Math object that provides a mathematical calculation of the data.

Using the properties and methods of Math, the code is as follows:

<script type= "Text/javascript" >
 var mypi=math.pi; 
 var myabs=math.abs ( -15);
 document.write (Mypi);
 document.write (myabs);
</script>

Run Result:

3.141592653589793
15

Note: The Math object is an intrinsic object that you can call all its properties and methods without creating it and using math as an object directly. This is the difference between it and the Date,string object.

Math Object Properties

Math Object method

Take the whole ceil up ()

The Ceil () method can be rounded up for a number.

Grammar:

Math.ceil(x)

Note : It returns an integer that is greater than or equal to X and is closest to X.

We will apply the Ceil () method to different numbers, the code is as follows:

<script type= "Text/javascript" >
 document.write (Math.ceil (0.8) + "<br/>")
 document.write ( Math.ceil (6.3) + "<br/>")
 document.write (Math.ceil (5) + "<br/>")
 document.write (Math.ceil (3.5) + "<br/>")
 document.write (Math.ceil ( -5.1) + "<br/>")
 document.write (Math.ceil ( -5.9))
< /script>

Run Result:

1
7
5
4
-5
-5

Take the whole floor down ()

The floor () method can be rounded down for a number.

Grammar:

Math.floor(x)

Parameter description:

Note : Returns an integer that is less than or equal to X and is closest to X.

We will use the floor () method on different numbers, and the code is as follows:

<script type= "Text/javascript" >
 document.write (Math.floor (0.8) + "<br>")
 document.write ( Math.floor (6.3) + "<br>")
 document.write (Math.floor (5) + "<br>")
 document.write (Math.floor (3.5 ) + "<br>")
 document.write (Math.floor ( -5.1) + "<br>")
 document.write (Math.floor ( -5.9))
</script>

Run Result:

0
6
5
3
-6
-6

Rounded round ()

The round () method rounds a number to the nearest integer.

Grammar:

Math.round(x)

Parameter description:

Attention:

Returns the nearest integer to X.

For 0.5, the method is rounded up. (5.5 will be rounded to 6)

If x is equal to the integers on both sides, the result is close to the numeric value in the +∞ direction. (If-5.5 will be rounded to-5;-5.52 will be rounded to-6), as shown in the following figure:

Round the different numbers to the nearest integer, the code is as follows:

<script type= "Text/javascript" >
 document.write (Math.Round (1.6) + "<br>");
 document.write (Math.Round (2.5) + "<br>");
 document.write (Math.Round (0.49) + "<br>");
 document.write (Math.Round ( -6.4) + "<br>");
 document.write (Math.Round ( -6.6));
</script>

Run Result:

2
3
0
-6
-7

Random number random ()

The random () method returns a random number between 0 ~ 1 (greater than or equal to 0 but less than 1).

Grammar:

Math.random();

Note: Returns a numeric value that is positive for a symbol greater than or equal to 0 but less than 1.

We get a random number between 0 and 1, and the code is as follows:

<script type= "Text/javascript" >
 document.write (Math.random ());
</script>

Run Result:

0.190305486195328

Note: because it is a random number, the results of each run are different, but the value of 0 ~ 1.

Get the random number between 0 ~ 10, the code is as follows:

<script type= "Text/javascript" >
 document.write ((Math.random ()) *10);
</script>

Run Result:

8.72153625893887

Array Arrays Object

An array object is a collection of objects that can have different types of objects. Each member object of an array has a "subscript" that represents its position in the array, starting from zero.

Array-defined methods:

1. An empty array is defined:

var  数组名= new Array();

2. Specify an array with n empty elements when defined:

var 数组名 =new Array(n);

3. When defining arrays, direct initialization of the data:

var  数组名 = [<元素1>, <元素2>, <元素3>...];

We define the MyArray array and assign a value to the code as follows:

var myArray = [2, 8, 6];

Description : Defines an array myarray, inside the element is: myarray[0] = 2; MYARRAY[1] = 8; MYARRAY[2] = 6.

Array elements are used:

Array name [subscript] = value;

Note: The subscript for the array is enclosed in square brackets, starting at 0.

Array properties:

Length usage:< Array Object >.length; return: The length of the array, that is, how many elements are in the array. It equals the subscript plus one of the last element in the array.

Array method:

Array Connection concat ()

The Concat () method is used to connect two or more arrays. This method returns a new array and does not change the original array.

Grammar

arrayObject.concat(array1,array2,...,arrayN)

Parameter description:

Note: This method does not change an existing array, but merely returns a copy of the connected array.

We create an array that connects the arguments in Concat () to the array Myarr, as follows:

<script type= "Text/javascript" >
 var mya = new Array (3);
 Mya[0] = "1";
 MYA[1] = "2";
 MYA[2] = "3";
 document.write (Mya.concat (4,5) + "<br>");
 document.write (mya); 
</script>

Run Result:

1,2,3,4,5
1,2,3

We created three arrays and then connected them using concat (), and the code was as follows:

<script type= "Text/javascript" >
 var mya1= new Array ("hello!")
 var mya2= new Array ("I", "Love");
 var mya3= new Array ("JavaScript", "!");
 var mya4=mya1.concat (MYA2,MYA3);
 document.write (MYA4);
</script>

Run Result:

hello!,I,love,JavaScript,!

Specifies the delimiter connection array element join ()

The join () method is used to put all elements in an array into a string. The elements are delimited by the specified delimiter.

Grammar:

arrayObject.join(分隔符)

Parameter description:

Note: Returns a string that strings each element of the array, using < separator > between elements and elements. This method does not affect the original contents of the array. We use the join () method to put all the elements of an array in a string, as follows:

<script type= "Text/javascript" >
 var myarr = new Array (3);
 Myarr[0] = "I";
 MYARR[1] = "Love";
 MYARR[2] = "JavaScript";
 document.write (Myarr.join ());
</script>

Run Result:

I,love,JavaScript

We'll use delimiters to separate the elements in the array, and the code is as follows:

<sript type= "Text/javascript" >
 var myarr = new Array (3)
 myarr[0] = "I";
 MYARR[1] = "Love";
 MYARR[2] = "JavaScript";
 document.write (Myarr.join ("."));
</script>

Run Result:

I.love.JavaScript

Reverse array element order reverse ()

The reverse () method reverses the order of elements in an array.

Grammar:

arrayObject.reverse()

Note : This method changes the original array without creating a new array.

Defines an array Myarr and assigns values, and then reverses the order of its elements:

<script type= "Text/javascript" >
 var myarr = new Array (3)
 myarr[0] = "1"
 myarr[1] = "2"
 myarr[2] = " 3 "
 document.write (Myarr +" <br/> ")
 document.write (Myarr.reverse ())
</script>

Run Result:

1,2,3
3,2,1

Selected element Slice ()

The slice () method returns the selected element from an existing array.

Grammar

arrayObject.slice(start,end)

Parameter description:

1. Returns a new array containing the elements in the arrayobject from start to end (excluding the element).

The method does not modify the array, but instead returns a child array.

Attention:

You can use negative values to select elements from the tail of an array.

2. If end is not specified, then the slice () method selects all elements from start to ending of the array.

String.slice () is similar to Array.slice ().

We will create a new array and then select the element from it, as follows:

<script type= "Text/javascript" >
 var myarr = new Array (1,2,3,4,5,6);
 document.write (Myarr + "<br>");
 document.write (Myarr.slice (2,4) + "<br>");
 document.write (Myarr);
</script>

Run Result:

1,2,3,4,5,6
3,4
1,2,3,4,5,6

Arrays Sort sort ()

The sort () method arranges the elements in an array in a certain order.

Grammar:

arrayObject.sort(方法函数)

Parameter description:

1. If you do not specify the < method function, it is arranged in Unicode code order.

2. If the < method function is specified, the sort method specified by the < method function > is sorted.

myArray.sort(sortMethod);

Note: The function compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B, and the return value is as follows:

If the return value is <=-1, it means that A in the sorted sequence appears before B.

The return value >-1 && <1 means that a and B have the same sort order. If the return value is >=1, it means that A in the sorted sequence appears after B.

1. Use sort () to sort the array with the following code:

<script type= "Text/javascript" >
 var myarr1 = new Array ("Hello", "John", "Love", "JavaScript"); 
 var myarr2 = new Array ("6", "N", "1", "+");
 document.write (Myarr1.sort () + "<br>");
 document.write (Myarr2.sort ());
</script>

Run Result:

Hello,javascript,john,love
1,100,16,50,6,80

Note: The code above does not sort the numbers by the size of the values.

2. To achieve this, you must use a sort function, the following code:

<script type= "Text/javascript" >
 function Sortnum (a,b) {return
 a-b;
 Ascending, as in descending order, "a-b" should be "B-a"
}
 var myarr = new Array ("6"
 , "X", "1"); document.write (Myarr + "<br>");
 document.write (Myarr.sort (Sortnum));
</script>

Run Result:

80,16,50,6,100,1
1,6,16,50,80,100

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

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.