Understand the built-in objects in JavaScript

Source: Internet
Author: User
Tags mathematical functions natural logarithm string methods javascript array
All programming languages have internal (or built-in) objects to create the basic functions of the language. An internal object is the language used to write Custom Code. The Code implements custom functions based on your imagination. JavaScript has many internal objects that define it as a language. This article introduces... SyntaxHighlighter. all (); all programming languages have internal (or built-in) objects to create the basic functions of the language. An internal object is the language used to write Custom Code. The Code implements custom functions based on your imagination. JavaScript has many internal objects that define it as a language. This article describes some of the most common objects and briefly describes what functions they have and how to use them.
 
Number
The JavaScript Number object is a value wrapper. You can combine it with the new keyword and set it to a variable to be used in JavaScript code later:
1
Var myNumber = new Number (numeric value );
Alternatively, you can create a Number object by setting a variable to a value. Then, the variable can access the available attributes and methods of the object.
In addition to numeric values, the Number object contains various attributes and methods used to operate or retrieve information about numbers. All available properties of the Number object are read-only constants, which means that their values remain unchanged and cannot be changed. Four attributes are included in the Number object:
● MAX_VALUE
● MIN_VALUE
● NEGATIVE_INFINITY
● POSITIVE_INFINITY
The MAX_VALUE attribute returns the 1.7976931348623157e + 308 value, which is the maximum number that JavaScript can process:
1
2
Document. write (Number. MAX_VALUE );
// Result is: 1.7976931348623157e + 308
In addition, use MIN_VALUE to return the 5e-324 value, which is the smallest number in JavaScript:
1
2
Document. write (Number. MIN_VALUE );
// Result is: 5e-324
NEGATIVE_INFINITY is the maximum negative number that JavaScript can process, expressed as-Infinity:
1
2
Document. write (Number. NEGATIVE_INFINITY );
// Result is:-Infinity
The POSITIVE_INFINITY attribute is any number greater than MAX_VALUE, which indicates Infinity:
1
2
Document. write (Number. POSITIVE_INFINITY );
// Result is: Infinity
There are also some methods for Number objects. You can use these methods to format or convert numeric values. These methods include:
● ToExponential
● ToFixed
● ToPrecision
● ToString
● ValueOf
Each method basically performs the operation indicated by its name. For example, the toExponential method returns the string representation of a number in an exponential form. Each method is unique in the parameters it accepts. The toExponential method has an optional parameter that can be used to set the number of valid numbers to be used. The toFixed method determines the decimal precision based on the passed parameters, the toPrecision method determines the valid number to be displayed based on the passed parameter.
Every object in JavaScript contains a toString and valueOf method, so these methods are not described in the previous section. The toString method returns the string representation of a number (in this example), but in other objects, it returns the string representation of the corresponding object type. The valueOf method returns the original value of the object type called. In this example, it is a Number object.
The Number object alone does not seem very powerful, but it is an important part of any programming language, and JavaScript is no exception. JavaScript Number objects provide the foundation for any mathematical program, which is basically the foundation of all programming languages.
 
Boolean
Boolean is necessary when trying to create any logic using JavaScript. Boolean is an object that represents true or false values. A Boolean object has multiple values, which are equivalent to false values (0,-0, null, or "" [an empty string]), undefined (NaN), and false. All other boolean values are equivalent to true. This object can be instantiated using the new keyword, but is usually a variable set to true or false:
1
Var myBoolean = true;
Boolean objects include the toString and valueOf methods, although you are unlikely to need these methods. Boolean is most commonly used for simple judgment of true or false values in condition statements. The combination of Boolean values and conditional statements provides a way to create logic using JavaScript. Examples of such conditional statements include if, if... Else, if... Else... If and switch statements. When used with a condition statement, you can use a Boolean value to determine the result based on the condition you have written. Listing 1 shows a simple example of combining conditional statements with Boolean values.
Listing 1. conditional statements combined with Boolean values
1
2
3
4
5
6
7
Var myBoolean = true;
If (myBoolean = true ){
// If the condition evaluates to true
}
Else {
// If the condition evaluates to false
}
It is self-evident that a Boolean object is an extremely important component of JavaScript. If no Boolean object exists, it cannot be determined in the Condition Statement.
 
String
JavaScript String objects are the wrapper of text values. In addition to text storage, the String object contains an attribute and various methods to operate or collect information about the text. Similar to a Boolean object, a String object can be used without being instantiated. For example, you can set a variable as a String, and all attributes or methods of the String object can be used for this variable:
1
Var myString = "My string ";
The String object has only one attribute, that is, length, which is read-only. The length attribute can be used to return only the length of a string: you cannot modify it externally. The subsequent Code provides an example of using the length attribute to determine the number of characters in a string:
1
2
3
Var myString = "My string ";
Document. write (myString. length );
// Results in a numeric value of 9
The result of this Code is 9, because the space between two words is also calculated as a character.
There are quite a few methods in the String object that can be used to operate and collect information about the text. The following is a list of available methods:
● CharAt
● CharCodeAt
● Concat
● FromCharCode
● IndexOf
● LastIndexOf
● Match
● Replace
● Search
● Slice
● Split
● Substr
● Substring
● ToLowerCase
● ToUpperCase
The chartAt method can be used to retrieve specific characters based on the index you pass as a parameter. The following code shows how to return the first character of a string:
1
2
3
Var myString = "My string ";
Document. write (myString. chartAt (0 );
// Results in M
If you need the opposite result, there are several methods to return the specified character or character set in the string without using the index to return the character. These methods include indexOf and lastIndexOf. Both methods contain two parameters: searchString and start. The searchString parameter is the start index, and the start parameter tells the method where to start searching. The difference between the two methods is that indexOf returns the first index and lastIndexOf returns the last index.
The charCodeAt method is similar to charAt: The only difference is that it returns Unicode characters. Another Unicode-related method (including in String objects) is fromCharCode, which converts Unicode to characters.
If you want to combine strings, you can add these strings by using the plus sign (+), or you can use the concat method more appropriately. This method accepts an infinite number of string parameters, connects them, and returns the combined result as a new string. Listing 2 shows how to use a concat instance to combine multiple strings into one.
Listing 2. Use the concat method to merge multiple strings
1
2
3
4
5
Var myString1 = "My ";
Var myString2 = "";
Var myString3 = "string ";
Document. write (myString. concat (myString1, myString2, myString3 );
// Results in "My String"
There is also a set of String methods that use regular expressions as a parameter to search for or modify a String. These include the match, replace, and search methods. The match method uses a regular expression to search for a specific string and returns all matched strings. The replace method actually accepts the substring or regular expression and the replacement string as its second parameter. replace all the matching items with the replacement string and return the updated string. The last of these methods is the search method, which searches for matching results of regular expressions and Returns their locations.
Multiple methods can be used to modify strings. The first method is the slice method, which extracts and returns a part of a string based on the combination of the start and end of the index or index. Another method is the split method. The split method Splits a string into a series of substrings whenever the delimiter parameter is found. For example, if you pass a comma (,) as a parameter, the string is split into a new substring at each comma. The method that can modify a string also includes the substr method, which extracts characters from a string based on the start position and length specified as the parameter, as well as the substring method, this method extracts characters from a string based on two indexes specified as parameters. The last method to change the string is toLowerCase and toUpperCase. They convert the characters in the string to lowercase and uppercase letters respectively. These methods are useful when comparing string values because strings may be case-insensitive. These methods ensure that you are comparing values, not case sensitive.
 
Date
The JavaScript Date object provides a way to process dates and times. You can instantiate it in many different ways, depending on the desired result. For example, you can instantiate a parameter without it:
1
Var myDate = new Date ();
Or pass milliseconds as a parameter:
1
Var myDate = new Date (milliseconds );
You can pass a date string as a parameter:
1
Var myDate = new Date (dateString );
Alternatively, you can pass multiple parameters to create a complete date:
1
Var myDate = new Date (year, month, day, hours, minutes, seconds, milliseconds );
In addition, there are several methods available for Date objects. Once the object is instantiated, you can use these methods. Most of the available methods focus on obtaining specific parts of the current time. The following method is the getter method that can be used for Date objects:
● GetDate
● GetDay
● GetFullYear
● GetHours
● GetMilliseconds
● GetMinutes
● GetMonth
● GetSeconds
● GetTime
● GetTimezoneOffset
As you can see, the value returned by each method is quite simple. The difference lies in the range of returned values. For example, the getDate method returns the number of days of a month, ranging from 1 to 31. The getDay method returns the number of days of a week, ranging from 0 to 6. The getHours method returns the number of hours, the value range is from 0 to 23. The getMilliseconds function returns a millisecond value, ranging from 0 to 999. The getMinutes and getSeconds Methods return a value ranging from 0 to 59. The getMonth method returns a month value from 0 to 11. The only unique methods in this list are getTime and getTimezoneOffset. The getTime method returns the number of milliseconds from noon on 1/1/1970, while the getTimezoneOffset method returns the time difference between the GMT Standard Time and the local time, in minutes.
For most getter methods, there is also a setter method that accepts numerical parameters in the corresponding value range. The setter method is as follows:
● SetDate
● SetFullYear
● SetHours
● SetMilliseconds
● SetMinutes
● SetMonth
● SetSeconds
● SetTime
For all the above getter methods, some matching methods return the same value range, but these values are set at International Standard Time. These methods include:
● GetUTCDate
● GetUTCDay
● GetUTCFullYear
● GetUTCHours
● GetUTCMilliseconds
● GetUTCMinutes
● GetUTCMonth
● GetUTCSeconds
Of course, because all the original getter methods have the setter method, the same is true for international standard time. These methods include:
● SetUTCDate
● SetUTCFullYear
● SetUTCHours
● SetUTCMilliseconds
● SetUTCMinutes
● SetUTCMonth
● SetUTCSeconds
As mentioned at the beginning of this article, I do not provide much information about the toString method, but there are some methods in the Date object that can convert the Date into a string, which is worth mentioning. In some cases, part of the date or date needs to be converted into a string. For example, if you append it to a string or use it in a comparison statement. There are several methods available for Date objects, which provide slightly different methods to convert them into strings, including:
● ToDateString
● ToLocaleDateString
● ToLocaleTimeString
● ToLocaleString
● ToTimeString
● ToUTCString
The toDateString method converts a date to a string:
1
2
Var myDate = new Date ();
Document. write (myDate. toDateString ());
ToDateString returns the current date in the format of Tue Jul 19 2011.
The toTimeString method converts the time from the Date object to a string:
1
2
Var myDate = new Date ();
Document. write (myDate. toTimeString ());
ToTimeString returns time as a string in the format of 23:00:00 GMT-0700 (MST ).
The last method to convert a date to a string is toUTCString, which converts a date to a string of International Standard Time.
There are several methods to convert a date to a string using region settings, but Google Chrome does not support these methods at the time of writing this article. Unsupported methods include toLocaleDateString, toLocaleTimeString, and toLocaleString.
The JavaScript Date object seems simple at first glance, but it is not just a useful way to display the current Date. It depends on the features you want to create. For example, the Date object is the basis for creating countdown watches or other time-related functions.
 
Array
JavaScript Array object is a variable that stores variables: You can use it to store multiple values in a variable at a time, it has many methods that allow you to operate or collect information about the values it stores. Although Array objects do not treat value types differently, it is good to use similar values in a single Array. Therefore, using numbers and strings in the same array is not a good practice. All attributes that can be used for Array objects are read-only, which means their values cannot be changed from outside.
The only attribute that can be used for Array objects is length. This attribute returns the number of elements in an array, which is usually used when the values in the array are iterated cyclically:
1
2
3
4
Var myArray = new Array (1, 2, 3 );
For (var I = 0; I Document. write (myArray [I]);
}
You can use multiple methods to add elements to an Array or delete elements from an Array. These methods include pop, push, shift, and unshift. Both the pop and shift Methods Delete elements from the array. The pop method deletes and returns the last element in an array, while the shift method deletes and returns the first element in an array. The opposite functions can be implemented through the push and unshift methods. They add elements to the array. The push method adds an element as the new element to the end of the array and returns the new length. The unshift method adds the element to the front of the array and returns the new length.
Array sorting in JavaScript can be achieved through two methods, one of which is actually called sort. Another method is reverse. The complexity of the sort method is that it sorts arrays based on optional sort functions. The sort function can be any custom function you have written. The reverse method is not as complex as sort, although it does change the order of elements in the array by reversing the elements.
When processing arrays, indexes are very important because they define the positions of each element in the array. There are two ways to change strings Based on indexes: slice and splice. The slice Method accepts the combination of index or index start and end as parameters, extracts part of the array, and returns it as a new array based on parameters. The splice method includes the index, length, and unlimited element parameters. This method adds an element to the Array Based on the specified index, deletes the element from the Array Based on the specified index, adds the element to the Array Based on the specified index, or deletes the element from the array. Another way is to return an index: indexOf Based on the matching value. Then you can use this index to intercept or splice arrays.
The key to writing good code in any programming language is to write well-organized code. As shown in various methods, JavaScript Array objects are a powerful way to organize data and create complex functions.
 
Math
The JavaScript Math object is used to execute mathematical functions. It cannot be instantiated: You can only use it as is based on the Math object, and call attributes and methods from this object without any instance:
1
Var pi = Math. PI;
Math objects have many attributes and methods that provide mathematical functions to JavaScript. All Math attributes are read-only constants, including the following:
● E
● LN2
● LN10
● LOG2E
● LOG10E
● PI
● SQRT1_2
● SQRT2
The E attribute returns the base number of the natural logarithm, or the Euler's index. This value is a unique real number named after Leonhard Euler. Call the E attribute to generate the number 2.718281828459045. The other two attributes are also used to return the natural logarithm: LN2 and LN10. The LN2 attribute returns the natural logarithm of 2, while the LN10 attribute returns the natural logarithm of 10. The LOG2E and LOG10E attributes can be used to return the base 2 or 10 logarithm of E. LOG2E returns 1.4426950408889633, while LOG10E returns 0.4342944819032518. Generally, you do not need most of these attributes unless you are building a calculator or other mathematical-intensive project. However, PI and square root are common. The PI method returns the ratio of the circumference to the diameter. The square root values of the two attributes are SQRT1_2 and SQRT2. The first property returns the square root of 0.5, while SQRT2 returns the square root of 2.
In addition to these attributes, there are several methods to return different values of a number. Each method accepts numeric values and returns a value based on the method name. Unfortunately, the method name is not always obvious:
● Abs. Absolute Value of a number
● Acos. Arccosine
● Asin. Arcsin
● Atan. Arc tangent
● Atan2. Returns the arc tangent of multiple numbers.
● Cos. Cosine
● Exp. Power
● Log. Natural logarithm of a number
● Pow. Y Power of x
● Sin. Sine
● Sqrt. Square Root
● Tan. Tangent of an angle
There are three methods to take integers in JavaScript: ceil, floor, and round. The ceil method returns the rounded up value of a number. This method is useful when you need to round up a number to the nearest integer. The floor method provides the opposite function of ceil: it returns the downward rounding value of a number. This method is useful when you want to forward numbers to the nearest integer. The round method provides a common rounding function to round up or down a number based on an existing number.
The last three methods in the Math object are max, min, and random. The max method accepts multiple numeric parameters and returns the highest value, while the min method accepts multiple numeric parameters and returns the lowest value. These methods are very useful when comparing variables with values, especially when you do not know what values are. You use the random method to return a random number between 0 and 1. You can use this method for multiple purposes, such as displaying a random image on the website homepage or returning a random number, which can be used as an index of the array of file paths containing images. The path of the random image file selected from the array can then be used to write the image to the HTML Tag.
 
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.