Understanding built-in objects in JavaScript

Source: Internet
Author: User
Tags mathematical functions natural logarithm square root

All programming languages have internal (or built-in) objects to create the basic functionality of the language. An internal object is the basis for the language in which you write custom code, which implements custom functionality based on your imagination. JavaScript has many internal objects that define it as a language. This article describes some of the most commonly used objects, and provides a brief overview of what they do and how to use them.

Number

Numbera JavaScript object is a numeric wrapper. You can use it in new conjunction with a keyword and set it as a variable to be used later in the JavaScript code:

var mynumber = new Number (numeric value);

Alternatively, you can create an object by setting a variable to a numeric value Number . The variable will then be able to access the properties and methods available to the object.

In addition to storing numeric values, Number objects contain various properties and methods for manipulating or retrieving information about numbers. Numberall properties available for an object are read-only constants , which means that their values are always unchanged and cannot be changed. There are 4 attributes contained in the Number object:

    • MAX_VALUE
    • MIN_VALUE
    • NEGATIVE_INFINITY
    • POSITIVE_INFINITY

MAX_VALUEProperty return 1.7976931348623157e+308 value, which is the maximum number that JavaScript can handle:

document.write (Number.MAX_VALUE);//Result is:1.7976931348623157e+308

Also, use the MIN_VALUE return 5e-324 value, which is the smallest number in JavaScript:

document.write (Number.min_value);//Result is:5e-324

NEGATIVE_INFINITYis the maximum number of negative numbers that JavaScript can handle, expressed as -Infinity :

document.write (number.negative_infinity);//Result is:-infinity

POSITIVE_INFINITYThe property is MAX_VALUE any number greater than, expressed as Infinity :

document.write (number.positive_infinity);//Result is:infinity

NumberObjects also have methods that you can use to format or convert numeric values. These methods include:

    • toExponential
    • toFixed
    • toPrecision
    • toString
    • valueOf

Each method basically performs the operation as implied by its name. For example, toExponential a method returns a string representation of a number as an exponent. The uniqueness of each method is the parameters it accepts. toExponentialmethod has an optional parameter that lets you set how many valid numbers to use, toFixed determines the decimal precision based on the parameters passed, and toPrecision determines the valid number to display based on the parameters passed.

Each object in JavaScript contains one toString and a valueOf method, so these methods are not covered in the previous chapters. toStringmethod returns a string representation of a number (in this case), but in other objects, it returns a string representation of the corresponding object type. valueOfmethod returns the original value of the object type that called it, in this case the Number object.

Objects only seem to be Number not very powerful, but it is an important part of any programming language, and JavaScript is no exception. JavaScript Number objects provide the basis for any mathematical program, which is basically the basis for all programming languages.

Back to top of page

Boolean

BooleanIt is necessary to try to create any logic with JavaScript. A Boolean is an object that represents a value of true or false. Booleanobjects have multiple values that correspond to false values ( 0 , -0 , null or "" [an empty string]), undefined (), and, NaN of course, false. All other Boolean values are equivalent to true values. The object can be new instantiated by a keyword, but it is usually a variable set to a value of TRUE or false:

var Myboolean = true;

BooleanObject includes toString and valueOf methods, although you are unlikely to need to use these methods. A Boolean simple judgment that is most commonly used in a conditional statement for a value of true or false. 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 in conjunction with a conditional statement, you can use a Boolean value to determine the result based on conditions that you write. Listing 1 shows a simple example of combining a conditional statement with a Boolean value.

Listing 1. Conditional statements that are combined with Boolean values
var Myboolean = true;if (Myboolean = = True) {   //If the condition evaluates to True}else {   //if the condition eval Uates to False}

It goes without saying that Boolean objects are an extremely important part of JavaScript. If there is no Boolean object, it cannot be judged within a conditional statement.

Back to top of page

String

Stringa JavaScript object is a wrapper for text values. In addition to storing text, String an object contains a property and various methods to manipulate or gather information about the text. Booleanlike objects, String objects do not need to be instantiated to be used. For example, you can set a variable to a string, and then String all properties or methods of the object are available to the variable:

var myString = "My string";

StringObject has only one property, that length is, it is read-only. lengthproperty can be used to return only the length of a string: You cannot modify it externally. The following code provides an example of using length properties to determine the number of characters in a string:

var myString = "My string";d ocument.write (mystring.length);//Results in a numeric value of 9

The result of the code is 9 that the space between two words is also calculated as a character.

StringThere are quite a few ways to manipulate and gather information about text in an object. The following is a list of available methods:

    • charAt
    • charCodeAt
    • concat
    • fromCharCode
    • indexOf
    • lastIndexOf
    • match
    • replace
    • search
    • slice
    • split
    • substr
    • substring
    • toLowerCase
    • toUpperCase

chartAtMethod can be used to retrieve a specific character based on the index that you pass as a parameter. The following code shows how to return the first character of a string:

var myString = "My string";d ocument.write (mystring.chartat (0);//Results in M

If you need the opposite result, there are several ways to return a specified character or character set in a string without using an index to return a character. These methods include indexOf and lastIndexOf , both of these methods contain two parameters: searchString and start . The searchString parameter is the starting index, and the start parameter tells the method where to start the search. The difference between the two methods is that the indexOf first index is returned, and the lastIndexOf last index is returned.

charCodeAtmethod is similar to charAt : The only difference is that it returns Unicode characters. Another method of Unicode-related (including in an String object) is fromCharCode that it converts Unicode to characters.

If you want to combine strings, you can use the plus sign ( + ) to add these strings together, or you can use the method more appropriately concat . The method accepts an infinite number of string arguments, joins them, and returns the synthesized result as a new string. Listing 2 shows how to use concat an instance to combine multiple strings into one.

Listing 2. Merging multiple strings using the Concat method
var myString1 = "My"; var myString2 = ""; var myString3 = "string";d ocument.write (Mystring.concat (myString1, MyString2, MyS TRING3);//Results in "My String"

There is also a set String of methods that accept a regular expression as a parameter to find or modify a string. These include match , replace and search methods. matchmethod uses a regular expression to search for a specific string and returns all matching strings. replacemethod actually takes a substring or regular expression and a replacement string as its second argument, replaces all occurrences with a replacement string, and returns the updated string. The last of these methods is the search method, which searches for the matching result of the regular expression and returns its position.

If you need to modify a string, there are several ways to use it. The first method is a slice method that extracts and returns a portion of a string based on the combination of the beginning and end of an index or index. Another method is the split method. splitmethod 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. Methods that can modify a string include substr methods that extract characters from a string based on the starting position and length specified as a parameter, and a substring method that extracts characters from a string based on two indexes that are specified as parameters. The last way to change the string is the toLowerCase and toUpperCase , respectively, they convert the characters in the string to lowercase and uppercase. These methods are useful when comparing string values because strings may sometimes be inconsistent in case. These methods ensure that you are comparing values, not case.

Back to top of page

Date

JavaScript Date objects provide a way to handle dates and times. You can instantiate it in many different ways, depending on the result you want. For example, you can instantiate a parameter without parameters:

var mydate = new Date ();

Or passed milliseconds as a parameter:

var mydate = new Date (milliseconds);

You can pass a date string as a parameter:

var mydate = new Date (datestring);

Or you can pass multiple parameters to create a full date:

var mydate = new Date (year, month, day, hours, minutes, seconds, milliseconds);

In addition, there are several ways to Date use the object, and once the object is instantiated, you can work with these methods. Most of the available methods revolve around getting a specific part of the current time. The following methods are getter methods that can be used Date with objects:

    • getDate
    • getDay
    • getFullYear
    • getHours
    • getMilliseconds
    • getMinutes
    • getMonth
    • getSeconds
    • getTime
    • getTimezoneOffset

As you can see, the values returned by each method are fairly straightforward. The difference is in the range of values returned. For example, the method returns the getDate number of days in a month, ranging from 1 to +, and the getDay method returns the number of days per week, ranging from 0 to 6, the getHours method returns the hour value, the range from 0 to a, getMilliseconds and the function returns a millisecond value ranging from 0 to 999. getMinutesand getSeconds methods return a value from 0 to 59, the getMonth method returns a month value from 0 to 11. The only unique method in this list is the getTime and getTimezoneOffset . The method getTime returns the number of milliseconds from 12 o'clock noon in 1/1/1970, and getTimezoneOffset the method returns the time difference, in minutes, between Greenwich Mean Time and local times.

For most getter methods, there is also a setter method that accepts numeric parameters within the corresponding value range. The setter method is as follows:

    • setDate
    • setFullYear
    • setHours
    • setMilliseconds
    • setMinutes
    • setMonth
    • setSeconds
    • setTime

For all of the getter methods above, there are some matching methods that return the same range of values, except those values are set at international time. These methods include:

    • getUTCDate
    • getUTCDay
    • getUTCFullYear
    • getUTCHours
    • getUTCMilliseconds
    • getUTCMinutes
    • getUTCMonth
    • getUTCSeconds

Of course, because there are setter methods for all primitive getter methods, 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 toString information about methods, but there are methods in the Date object that can convert dates to a string, which is worth mentioning. In some cases, you need to convert a part of a date or date to 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 that provide a slightly different way to convert them into strings, including:

    • toDateString
    • toLocaleDateString
    • toLocaleTimeString
    • toLocaleString
    • toTimeString
    • toUTCString

toDateStringmethod to convert a date to a string:

var mydate = new Date ();d ocument.write (mydate.todatestring ());

toDateStringReturns the current date in the format Tue Jul 19 2011.

toTimeStringmethod to convert the time from Date an object to a string:

var mydate = new Date ();d ocument.write (mydate.totimestring ());

toTimeStringReturns the time as a string in the format 23:00:00 GMT-0700 (MST).

The last way to convert a date to a string is toUTCString to convert the date to a string of international standard Time.

There are several ways to convert dates to strings using locale settings, but Google Chrome does not support these methods at the time of writing this article. Unsupported methods include toLocaleDateString , toLocaleTimeString and toLocaleString .

Datethe JavaScript object may seem simple at first, but it is not just a useful way to display the current date. It depends on the feature you are creating. For example, Date an object is the basis for creating a countdown clock or other time-related functionality.

Back to top of page

Array

A JavaScript Array object is a variable that stores variables: You can use it to store multiple values in one variable at a time, and it has many ways to allow you to manipulate or collect information about the values it stores. Although Array objects do not discriminate between value types, it is good practice to use homogeneous values in a single array. Therefore, it is not a good practice to use numbers and strings in the same array. All properties that are available to an Array object are read-only, which means that their values cannot be changed externally.

The only property that can be used for an Array object is length . This property returns the number of elements in an array, which is typically used when using values from a loop iteration group:

var myArray = new Array (1, 2, 3), for (var i=0; i<myarray.length; i++) {   document.write (myarray[i]);}

There are several methods available for Array objects, and you can use various methods to add elements to an array, or to delete an element from an array. These methods include pop , push ,, shift and unshift . popand shift methods both remove elements from the array. popmethod deletes and returns the last element in an array, and the shift method deletes and returns the first element in an array. The opposite features can be push implemented by and unshift methods, which add elements to the array. The push Add method adds the element to the end of the array as a new element and returns the new length, while the unshift method adds the element to the front of the array and returns the new length.

Sorting an array in JavaScript can be done in two ways, one of which is actually called a sort . Another way is reversesortthe complexity of a method is that it arranges arrays based on an optional sort function. sortThe function can be any custom function that you write. reversethe method is not as complex as that sort , although it does change the order of the elements in the array by reversing the elements.

Indexes are important when working with arrays because they define the position of each element in the array. There are two ways to change a string based on an index: slice and splice . The slice method accepts a combination of index or index start and end as a parameter, then extracts part of the array and returns it as a new array based on the parameter. splicemethods include index , length and unlimited element parameters. The method adds an element to an array based on the specified index, removes the element from the array based on the specified index, or adds the element to the array or removes the element from the array, based on the specified index. There is also a way to return an index based on a matching value: indexOf . You can then use the index to intercept or splice an array.

The key to writing good code in any programming language is to write organized code. As its various methods show, JavaScript Array objects are a powerful way to organize your data and create complex features.

Back to top of page

Math

JavaScript Math objects are used to perform mathematical functions. It cannot be instantiated: You can only Math use it based on the object, and invoke properties and methods from the object without any instances:

var pi = Math.PI;

MathObjects have many properties and methods that provide mathematical functionality to JavaScript. All Math properties are read-only constants, including the following:

    • E
    • LN2
    • LN10
    • log2e
    • log10e
    • PI
    • sqrt1_2
    • SQRT2

Eproperty returns the base value of the natural logarithm, or Euler exponent. The value is the only real number, named Leonhard Euler. Calling a E property yields the number 2.718281828459045. The other two properties are also used to return the natural logarithm: LN2 and LN10 . The property returns a natural logarithm with a LN2 value of 2, and the LN10 property returns a natural logarithm of 10. LOG2Eand LOG10E properties can be used to return a E logarithm with a base of 2 or 10. LOG2EThe result is 1.4426950408889633, and LOG10E the result is 0.4342944819032518. Typically, you don't need most of these properties unless you're building a calculator or other math-intensive project. However, the PI square root is more common. PImethod returns the ratio of circumference to diameter. Two properties return the square root value: SQRT1_2 and SQRT2 . The first property returns the square root of 0.5, and SQRT2 the square root of 2.

In addition to these properties, there are several ways to return different values for a number. Each of these methods accepts numeric values and returns a value based on the method name. Unfortunately, the method name is not always obvious:

    • ABS . the absolute value of a number
    • acos . inverse cosine
    • ASIN . Inverse string
    • atan . anyway tangent
    • atan2 . inverse tangent of multiple numbers
    • cos . cosine
    • exp . Power
    • log . the natural logarithm of a number
    • pow . x's y-square value
    • sin . sine
    • sqrt . square root
    • Tan . tangent of one corner

There are three ways to take integers in JavaScript: ceil , floor and round . ceilmethod returns a number that is rounded up by a value. This method is useful when you need to round a number up to the nearest integer. The floor method provides the ceil opposite function: it returns the downward rounded value of a number. This method is useful when you need to round down a number to the nearest integer. The round method provides a normal rounding function that rounds a number up or down based on an existing decimal.

MathThe last three methods included in the object are max , and, respectively min random . maxthe 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 useful when comparing variables that have numeric values, especially if you do not know what values are in advance. You use random the method to return a random number between 0 and 1. You can use this method for a variety of purposes, such as displaying a random image on the home page of a site, or returning a random number that can be used as an index to an array of file paths that contain images. The random image file path selected from the array can then be used to write the image to an HTML tag.

Back to top of page

Conclusion

The properties and methods provided by JavaScript are only the beginning of functionality that can be implemented: your imagination has created custom features. Because your imagination has no boundaries, there is no limit to the code you write. JavaScript is a flexible language that sometimes makes it a bad name, but on the bright side, it also gives you the ability to write code quickly and creatively. To learn more about JavaScript objects and how to create your own custom objects in the JavaScript language, be sure to review the Resources section.

Understanding built-in objects in JavaScript

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.