In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the commonly used objects in JavaScript", friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the commonly used objects in JavaScript"?
The common objects in JavaScript are: 1, array object (Array); 2, string object (String); 3, date-time object (Date); 4, Globle object; 5, window object; 6, Math object.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
Array
How to create an array
Just like object creates an object, it is created using the Array constructor, as shown in the following code
Var colors = new Array ()
Create an array literally
Var colors = []
Detection array
Determine whether a value is an array or not
Var colors = ['red','green','blue']; if (Array.isArray (colors)) {/ / perform some operations on a logarithmic array}
Conversion method
Calling the toString () method of the array returns a comma-separated string concatenated by the string of each value in the array.
Var colors = ['red','green','blue']; alert (colors.toString ()); / / red,green,blue
In addition, the toLocalString () method often returns the same value as the toString () method, but this is not always the case. For example:
Var person1 = {toLocaleString: function () {return'Ma Shuai';}, toString: function () {return'Ma Xiaoshuai';}} var person2 = {toLocaleString: function () {return 'next door Lao Wang';}, toString: function () {return 'next door Lao Li';}} var people = [person1,person2]; alert (people) / / Ma Xiaoshuai, Lao Li alert (people.toString ()); / Ma Xiaoshuai, Lao Li alert (people.toLocaleString ()) next door; / / Ma Dashuai, Lao Wang next door
Two objects are defined: person1 and person2. A toString () method and a toLocalString () method are defined for each object, and each method returns a different value. Then, create an array containing the two objects defined earlier. When you pass the array to alert (), the output is Ma Xiaoshuai and Lao Li next door. Because calling the toString () method of each item in the array (again, this is the same as the next line showing the result of calling the toString () method. When the toLocalString () method of each item in the array is called.
Split string
Both the toLocalString () method and the toString () method are returned as comma-separated strings by default. If you use the join () method, the join () method takes only one parameter.
Var colors = ['red','blue','green']; colors.join (' | |'); / / red | | blue | | green
Stack method
Arrays can also, like stacks, insert and delete the data structures of items. Stack is a LIFO (Last-In-First-Out, last-in, first-out) data structure, that is, the newly added element is the first to be deleted. The insertion (called push) and removal (called pop-up) of items in the stack occur only in one place-- at the top of the stack. Arrays specifically provide push () and pop () methods to implement stack-like behavior.
Push () method
You can take any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
Var colors = []; var count = colors.push ('red','blue','green'); alert (count); / / 3
Pop () method
Removes the last item from the end of the array, reduces the length value of the array, and then returns the removed item.
Var item = colors.pop (); / / take the last item alert (item); / / greenalert (colors.length); / / 2
Queuing method
The access rule of stack data structure is LIFO (LIFO), while the access rule of queue data structure is FIFO (First-In-First-Out). The queue adds items at the end of the list and removes items from the front of the list. Because push () is a way to add items to the end of an array, all you need to simulate a queue is a way to get items from the front end of the array. The array method that does this is shift (), which removes the first item in the array and returns it, while subtracting the length of the array by 1. Using the shift () and push () methods together, you can use arrays like queues.
Shift () method
Var colors = ['red','blue','green']; var item = colors.shift (); / / get the first alert (item); / / "red" alert (colors.length); / / 2
Unshift () method
ECMAScript also provides a unshift () method for arrays. As the name implies, unshift () is the opposite of shift (): it can add any item to the front of the array and return the length of the new array. Therefore, using both the unshift () and pop () methods, you can 12 simulate the queue in the opposite direction, adding items at the front of the array and removing items from the end of the array.
Var colors = []; var count = colors.unshift ('red','green'); / / push two alert (count); / / 2console.log (colors); / / ["red", "green"]
Reordering method
There are already two methods in the array that can be used directly to reorder: reverse () and sort ().
Reverse () method
Reverse flips the order of array items
Var values = [1, 2, 3, 4, 5]; values.reverse (); alert (values); / / 5, 4, 4, 5, 4, 5, 5, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 5, 4, 5, 4, 4, 4, 4, 4, 4, 1
Sort () method
By default, the sort () method is sorted in ascending order-- that is, the smallest value comes first and the largest value comes last. To achieve sorting, the sort () method calls the toString () transformation method for each array item, and then compares the resulting strings to determine how to sort them. Even if each item in the array is a numeric value, the sort () method compares a string. As shown below.
Var values = [0Jing 1, 5, 10, 15]; varlus.sort (); alert (values); / / 0, 1, 1, 10, 15, and 5
As you can see, even if there is no problem with the order of the values in the example, the sort () method changes the original order based on the results of the test string. Because the value 5 is less than 10, but when comparing strings, "10" comes before "5", so the order of the array is changed. Needless to say, this sort of sorting is not the best solution in many cases.
So the sort () method can take a comparison function as an argument so that we can specify which value precedes which value. To complete the ascending and descending functions of the values in the array
The comparison function takes two arguments, returns a negative number if the first parameter is before the second parameter, 0 if the two parameters are equal, and a positive number if the first parameter comes after the second parameter. For example:
Function compare (v1 and v2) {if (v1)
< v2){ return -1; }else if (v1 >V2) {return 1;} else {return 0;}}
This comparison function can be applied to most data types, as long as it is passed as an argument to the sort () method, as shown in the following example.
Var values = [0Jing 1jin5jue 10jue 15]; values.sort (compare); alert (values); / / 0Jing 1Jing 5jue 10jue 15
After passing the comparison function to the sort () method, the values still maintain the correct ascending order. Of course, you can also produce descending sort results by comparing functions, as long as you swap the values returned by the comparison function.
Function compare (v1 and v2) {if (v1)
< v2){ return 1; }else if (v1 >V2) {return-1;} else {return 0;}} var values = [0,1,5 values.sort 10, 15]; values.sort (compare); alert (values); / / 15 record10, 5, 5, 1, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10, 5, 5, 5, 1, 5, 5, 5, 1, 5, 5, 1, 5, 5, 1, 5, 5, 5, 1, 5, 5, 1, 5, 5, 1, 5, 1, 5, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5, 1, 5,
The comparison function returns 1 in cases where the first value should be after the second, and-1 in cases where the first value should be before the second. Swapping return values means higher ranking of larger values, that is, sorting the array in descending order. Of course, it's faster to use the reverse () method if you just want to reverse the original order of the array.
Operation method
ECMAScript provides many ways to manipulate items that are already included in the data. It contains things like concat (), slice (), and splice () to manipulate the items of the array.
Concat () method
The array merge method, where one array calls the concat () method to merge another array and returns a new array. The parameters received by concat () can be arbitrary.
Parameter is one or more arrays, the method adds each item in these arrays to the result array.
Parameter is not an array, these values are simply added to the end of the result array
Var colors = ['red','blue','green']; colors.concat (' yello'); / / ["red", "blue", "green", "yello"] colors.concat ({'name':' Zhang San'}); / / ["red", "blue", "green", {… }] colors.concat ({'name':' Li Si'}, ['black','brown']); / / ["red", "blue", "green", {… }, "black", "brown"]
Slice () method
The slice () method, which creates a new array based on one or more items in the current array. The slice () method can accept one or two parameters, both to return the start and end positions of the item.
In the case of one parameter, the slice () method returns all items from the specified position of the parameter to the default of the current array
In the case of two parameters, the method returns the item between the start and end positions-- but not the end position.
Note: the slice () method does not affect the original array
Var colors = ['red','blue','green','yellow','purple']; colors.slice (1); / / ["blue", "green", "yellow", "purple"] colors.slice (1mem4); / / ["blue", "green", "yellow"]
If there is a negative number in the parameters of the slice () method, the array length plus that number is used to determine the location of the response. For example, calling slice (- 2) on an array of 5 items is the same as calling slice (3). If the technical position is less than the starting position, an empty array is returned.
Var colors = ['red','blue','green','yellow','purple']; colors.slice (- 2 yellow); / / ["yellow"] colors.slice (- 1); / / []
Splice () method
The splice () method is probably the most powerful array method, and it can be used in many ways.
The main purpose of splice () is to insert thoughts into the middle of an array. There are three ways to use this method.
Delete: you can delete any number of items by specifying two parameters: the location of the first item to be deleted and the number to delete. For example, splice (0Pol 2) deletes the first two items in the array
Insert: you can insert any number of items into a specified location by providing three parameters: the starting position, 0 (the number to be deleted), and the item to be inserted. If you want to insert multiple items, you can pass in the fourth, fifth, or even any number of items. For example, splice will insert the strings' red' and 'green'' starting at position 2 of the current array.
Replace: you can insert any number of items into a specified location and delete any number of items at the same time, just specify three parameters: the starting position, the number of items to delete, and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2 red 1, "red", "green") deletes the entry at position 2 of the current array, and then inserts the strings "red" and "green" from position 2.
The splice () method always returns an array containing items deleted from the original array (or an empty array if no items are deleted).
Var colors = ["red", "green", "blue"]; var removed = colors.splice (0removed 1); alert (colors); / / green,blue alert (removed); / / red. The returned array contains only one item removed = colors.splice (1,0, "yellow", "orange"); alert (colors); / / green,yellow,orange,blue alert (removed). / / an empty array removed = colors.splice (1,1, "red", "purple"); alert (colors); / / green,red,purple,orange,blue alert (removed); / / yellow is returned. The returned array contains only one item.
Location method
ECMAScript 5 adds two location methods for array instances: indexOf () and lastIndexOf (). Both methods take two parameters: the item to find and (optional) an index that represents the location of the starting point for the lookup. Where the indexOf () method looks backward from the beginning of the array (position 0), and the lastIndexOf () method looks forward from the end of the array.
Both methods return the location of the item you are looking for in the array, or-1 if not found. When comparing the first parameter with each item in the array, the congruence operator is used; that is, the items to be found must be exactly equal (just like using = =). Take a chestnut:
Var numbers = [1 name (4)); / / 3alert (numbers.lastIndexOf (4)); / / 5alert (numbers.indexOf (4)); / / 5alert (numbers.lastIndexOf (4)); / / 3var person = {name: "mjj"}; var people = [{name:'mjj'}]; var morePeople = [person]; alert (people.indexOf (person)); / /-1alert (morePeople.indexOf (person)); / / 0
Iterative method
ECMAScript 5 defines five iterative methods for arrays.
Every ()
Some ()
Filter ()
Map ()
ForEach ()
The last three are commonly used here, and we will only introduce the last three.
Filter () method
The filter () function, which uses the specified function to determine whether to include an item in the returned array. For example, to return an array with all values greater than 2, you can use the following code.
Var numbers = [1 return (item, index, array) {return (item > 2);}); alert (filterResult); / / [3Jing 4 Jing 5 Jing 4 Jing 3]
Map () method
The map () method also returns an array, and each item in this array is the result of running the input function on the corresponding item in the original array. For example, you can multiply each item in an array by 2 and return an array of these products, as shown below
Var numbers = [1, item, index, array) {return item * 2;}); alert (filterResult); / / [2, 4, 6, 8, 10, 8, 10, 4, 4, 4, 4, 4, 4, 2]
ForEach () method
It simply runs the passed-in function on each item in the array. This method does not return a value, which is essentially the same as iterating over an array using a for loop. Let's look at an example.
/ / perform some operations 10var numbers = [1 function (item, index, array) {})
These array methods can greatly facilitate the processing of array tasks by performing different operations.
String
Each instance of the String type has a length property that indicates that the string contains multiple characters
Var stringValue = "hello world"; alert (stringValue.length); / / "11"
This example outputs the number of characters in the string "hello world", that is, "11"
1. Character method
Two methods for accessing specific characters in a string are charAt () and charCodeAt (). Both methods receive one parameter, the character position based on 0. Where the charAt () method returns the character at the given position as a single character string (there is no character type in ECMAScript).
For example:
Var stringValue = "hello world"; alert (stringValue.charAt (1)); / / "e"
The character at position 1 of the string "hello world" is "e", so a call to charAt (1) returns "e". If what you want is not a character but a character encoding, use charCodeAt () like this.
Var stringValue = "hello world"; alert (stringValue.charCodeAt (1)); / / output "101"
This example outputs "101", the character encoding of the lowercase letter "e".
ECMAScript 5 also defines another way to access individual characters. In browsers that support this method, you can use square brackets plus a numeric index to access specific characters in a string, as shown in the following example.
Var stringValue = "hello world"; alert (stringValue [1]); / / "e"
two。 String operation method
Here are several methods related to manipulating strings.
Concat ()
Used to concatenate one or more strings, 7 returns the new string. Let's take a look at an example.
Var stringValue = "hello"; var result = stringValue.concat ("world"); alert (result); / / "hello world" alert (stringValue); / / "hello"
In this example, the result returned by calling the concat () method through stringValue is "hello world"-- but the value of stringValue remains the same. In fact, the concat () method can accept any number of parameters, which means that it can be used to concatenate any number of strings. Look at another example:
Var stringValue = "hello"; var result = stringValue.concat ("world", "!"); alert (result); / / "hello world!" Alert (stringValue); / / "hello"
This example combines "world" and "!" Spliced to the end of "hello". Although concat () is a special method for concatenating strings, the plus operator (+) is more often used in practice. Also, using the plus operator is easier in most cases than using the concat () method (especially when concatenating multiple strings).
ECMAScript also provides three methods for creating new strings based on substrings: slice (), substr (), and substring (). All three methods return a substring of the string being manipulated, and all accept one or two parameters. The first parameter specifies the start position of the string, and the second parameter (in the specified case) indicates where the string ends.
Specifically, the second parameter of slice () and substring () specifies the position after the last character of the string.
The second parameter of substr () specifies the number of characters returned. If no second argument is passed to these methods, the length of the string is taken as the end position.
Like the concat () method, slice (), substr (), and substring () do not modify the value of the string itself-- they just return a string value of a basic type and have no effect on the original string. Take a look at the example below.
Ar stringValue = "hello world"; alert (stringValue.slice (3)); / / "lo world" alert (stringValue.substring (3)); / / "lo world" alert (stringValue.substr (3)); / / "lo world" alert (stringValue.slice (3)); / / "lo w" alert (stringValue.substring (3)); / / "lo w" alert (stringValue.substr (3)); / / "lo worl"
This example compares the results of calling slice (), substr (), and substring () in the same way, and the results are the same in most cases. When only one parameter 3 is specified, all three methods return "lo world" because the second "l" in "hello" is in position 3. When two parameters 3 and 7 are specified, slice () and substring () return "lo w" (the "o" in "world" is in position 7, so the result does not include "o"), but substr () returns "lo worl" because its second parameter specifies the number of characters to return.
When the parameters passed to these methods are negative, their behavior is different. Where the slice () method adds the negative value passed to the length of the string, and the substr () method adds the negative first argument to the length of the string, and converts the negative second argument to 0. Finally, the substring () method converts all negative parameters to 0. Let's look at an example.
Var stringValue = "hello world"; alert (stringValue.slice (- 3)); / / "rld" alert (stringValue.substring (- 3)); / / "hello world" alert (stringValue.substr (- 3)); / / "rld" alert (stringValue.slice (3,-4)); / / "lo w" alert (stringValue.substring (3,-4)); / / "hel" alert (stringValue.substr (3,-4)); / / "(empty string)
This example clearly shows the different behaviors between the above three methods. When you pass a negative parameter to slice () and substr (), they behave the same. This is because-3 is converted to 8 (string length plus parameter 11 + ( 3) = 8), which is actually equivalent to calling slice (8) and substr (8). But the substring () method returns all the strings because it converts-3 to 0.
When the second parameter is negative, the behavior of the three methods is different. The slice () method converts the second argument to 7, which is equivalent to a call to slice (3. 7), so it returns "lo w". The substring () method converts the second argument to 0, making the call substring (3jin0), and because this method takes a smaller number as the start position and a larger number as the end position, it ends up calling substring (0jin3). Substr () also converts the second parameter to 0, which means that a string containing zero characters is returned, which is an empty string.
3. String position method
There are two ways to look up substrings from a string: indexOf () and lastIndexOf (). Both methods search for a given substring from a string and return the location of the substring (or-1 if the substring is not found). The difference between the two methods is that the indexOf () method searches the substring backward from the beginning of the string, while the lastIndexOf () method searches the substring forward from the end of the string.
IndexOf () and lastIndexOf ()
Var stringValue = "hello world"; alert (stringValue.indexOf ("o")); / / 4alert (stringValue.lastIndexOf ("o")); / / 7alert (stringValue.indexOf ("o", 6)); / / 7alert (stringValue.lastIndexOf ("o", 6)); / / 4
4.trim () method
ECMAScript 5 defines the trim () method for all strings, removing the spaces before and after the string.
Var stringValue = "hello world"; var trimmedStringValue = stringValue.trim (); alert (stringValue); / / "hello world" alert (trimmedStringValue); / / "hello world"
5. String case conversion method
There are four .toLowerCase (), toLocaleLowerCase (), toUpperCase (), and toLocaleUpperCase () methods involved in string case conversion in ECMAScript. ToLowerCase () and toUpperCase () are two classic methods, while the toLocaleLowerCase () and toLocaleUpperCase () methods are region-specific implementations. For some regions, the result of the region-specific method is the same as that of the general method, but a few languages (such as Turkish) will apply special rules for Unicode case conversion, so the region-specific method must be used to ensure the correct conversion.
Var stringValue = "hello world"; alert (stringValue.toLocaleUpperCase ()); / / "HELLO WORLD" alert (stringValue.toUpperCase ()); / / "HELLO WORLD" alert (stringValue.toLocaleLowerCase ()); / / "hello world" alert (stringValue.toLowerCase ()); / / "hello world" Date date
The Date type in ECMAScript is built on the java.util.Date class in the earlier Java. To do this, the Date type saves the date using the number of milliseconds that have elapsed since midnight (00:00) on January 1, 1970, UTC (Coordinated Universal Time). Using this data storage format, the date saved by the Date type can be accurate to 285,616 years before or after January 1, 1970.
To create a date object, use the new operator and the Date constructor, as shown below
Var now = new Date ([parameters])
The parameter (parameters) in the preceding syntax can be any of the following:
No parameter: create today's date and time, for example: var today = new Date ();.
A string representing the date in the following format: "month, day, year: minutes: seconds." For example: var Xmas95 = new Date ("December 25, 1995 13:30:00"). If you omit hours, minutes, and seconds, their values will be set to 0.
A collection of integer values for a year, month, and day, for example: var Xmas95 = new Date (1995, 11, 25).
A collection of years, months, days, hours, minutes and seconds, for example: var Xmas95 = new Date (1995, 11, 25, 9, 30, 0);.
Methods of Date object
Date formatting method
The Date type also has some special methods for formatting dates into strings, as follows.
ToDateString ()-displays the day, month, day, and year in an implementation-specific format
ToTimeString ()-displays hours, minutes, seconds, and time zones in an implementation-specific format
ToLocaleDateString ()-displays the day, month, day, and year in a region-specific format
ToLocaleTimeString ()-displays hours, minutes, and seconds in an implementation-specific format
ToUTCString ()-- A complete UTC date in an implementation-specific format.
Var myDate = new Date ()
ToDateString ()
MyDate.toDateString (); / / "Mon Apr 15 2019"
ToTimeString ()
MyDate.toTimeString () / / "10:11:53 GMT+0800 (China Standard time)"
ToLocaleDateString ()
MyDate.toLocaleDateString (); / / "2019-4-15"
ToLocaleTimeString ()
MyDate.toLocaleTimeString (); / / "10:11:53"
ToUTCString ()
MyDate.toUTCString (); / / "Mon, 15 Apr 2019 02:11:53 GMT"
Chestnut: returned the time in digital clock format
Var time = new Date (); var hour = time.getHours (); var minute = time.getMinutes (); var second = time.getSeconds (); var temp = "" + ((hour > 12)? Hour-12: hour); if (hour = = 0) temp = "12"; temp + = (minute
< 10) ? ":0" : ":") + minute;temp += ((second < 10) ? ":0" : ":") + second;temp += (hour >= 12)? "P.M.": "A.M."; alert (temp); conversion between string and numeric value
String transfer value
Var str = '123.0000111 consolation console.log (parseInt (str)); console.log (typeof parseInt (str)); console.log (parseFloat (str)); console.log (typeof parseFloat (str)); console.log (Number (str))
Numeric to string
Var num = 1233.006ramp / cast console.log (String (num)); console.log (num.toString ()); / / implicit conversion console.log ('.concat (num)); / / toFixed () method rounds console.log (num.toFixed (2)) based on the string that returns a numeric value by the specified decimal place; the Globle object
The Global object can be said to be the most special object in ECMAScript, because no matter how you look at it, it doesn't exist. In a sense, the Global object in ECMAScript is defined as the ultimate "backing object". In other words, properties and methods that do not belong to any other object are ultimately its properties and methods. In fact, there are no global variables or global functions; all properties and functions defined in the global scope are properties of the Global object. The functions described earlier in this book, such as isNaN (), isFinite (), parseInt (), and parseFloat (), are actually all methods of the Global object. In addition, the Global object contains other methods.
URI coding method
The encodeURI () and encodeURIComponent () methods of the Global object can encode the URI (Uniform Resource Identifiers, universal resource identifier) for sending to the browser. Valid URI cannot contain certain characters, such as 5 spaces. These two URI encoding methods can encode URI, replacing all invalid characters with a special UTF-8 encoding, so that browsers can accept and understand it.
Where encodeURI () is mainly used for the entire URI (for example, [http://www.apeland/web index.html] (http://www.apeland/web index.html)), while encodeURIComponent () is mainly used to encode a segment in the URI (such as web index.html in the previous URI). The main difference between them is that encodeURI () does not encode special characters that belong to URI, such as colons, forward slashes, question marks, and pit characters, while encodeURIComponent () encodes any non-standard characters it finds, for example.
Var url = `index.html`; console.log (encodeURI (url)); / / http://www.apeland/web%20index.htmlconsole.log(encodeURIComponent(url));//http%3A%2F%2Fwww.apeland%2Fweb%20index.html
The result of encoding with encodeURI () is that all characters except spaces are intact, only spaces are replaced with% 20. The encodeURIComponent () method replaces all non-alphanumeric characters with the corresponding encoding.
In general, we use the encodeURIComponent () method more often than encodeURI (), because in practice it is more common to encode the query string parameters rather than the underlying URI.
The two methods corresponding to the encodeURI () and encodeURIComponent () methods are decodeURI () and decodeURIComponent (), respectively. Where decodeURI () can only decode characters replaced with encodeURI (). For example, it can replace% 20 with a space, but will not do anything with% 23 because% 23 represents a hyphen (#), and the hyphen is not replaced with encodeURI (). Similarly, decodeURIComponent () can decode using encodeURIComponent () encoding
Window object
Although ECMAScript does not indicate how to access the Global object directly, Web browsers implement this global object as part of the window object. Therefore, all variables and functions declared in the global scope become properties of the window object. Let's look at the following example.
Var color = "red"; function sayColor () {alert (window.color);} window.sayColor (); / / "red" Math object
ECMAScript also provides a common place to store mathematical formulas and information, that is, Math objects. Compared to the computing capabilities we wrote directly in JavaScript, the computing capabilities provided by Math objects are much faster to perform. Properties and methods to assist in these calculations are also provided in the Math object.
Properties of the 1.Math object
Most of the properties contained in the Math object are special values that may be used in mathematical calculations. The following table lists these properties
The attribute describes the base of the Math.E natural logarithm, that is, the value of the constant e, the natural logarithm of Math.LN1010, the natural logarithm of Math.LN22, the natural logarithm of Math.LN22, the logarithm of 2, the logarithm of e, the square root of Math.PI π, the square root of Math.SQRT1_21/2 (that is, the reciprocal of the square root of 2), the square root of Math.SQRT22.
2.min () and max () methods
The Math object also contains many methods to assist in simple and complex mathematical calculations.
Where the min () and max () methods are used to determine the minimum and maximum values in a set of values. Both methods can receive any number of numeric parameters, as shown in the following example
Var max = Math.max (3,54,32,16); alert (max); / / 54var min = Math.min (3,54,32,16); alert (min); / / 3
These two methods are often used to avoid redundant loops and to determine the maximum value of a set of numbers in if statements.
Example:
To find the maximum or minimum value in an array, you can use the apply () method as follows
Var values = [1, var max 2, 36, 23, 43, 3, 41]; var max = Math.max.apply (null, values)
The key to this trick is to set the this value correctly by taking the Math object as the first parameter of apply (). You can then take any array as the second parameter.
3. Rounding method
Several methods for rounding decimal values to integers: Math.ceil (), Math.floor (), and Math.round (). These three methods follow the following rounding rules, respectively:
Math.ceil () performs up rounding, that is, it always rounds the value up to the nearest integer
Math.floor () performs down rounding, that is, it always rounds the value down to the nearest integer
Math.round () performs standard rounding, that is, it always rounds the number to the nearest integer (this is also the rounding rule we learned in math class).
Var num = 25.7 Math.round num2 = 25.2 flagship alerts (Math.ceil (num)); / / 26alert (Math.floor (num)); / / 25alert (Math.round (num)); / / 26alert (Math.round (num2)); / / 25
4.random () method
The Math.random () method returns a random number greater than or equal to 0 and less than 1.
Example 1: get an integer in the range from min to max
Function random (lower, upper) {return Math.floor (Math.random () * (upper-lower)) + lower;}
Example 2: get random colors
/ * generate a random rgb color * @ return {String} returns the contents of the color RGB value string, such as: rgb (201,57,96) * / function randomColor () {/ / randomly generate rgb values, each color value between 0255r = random (0256), g = random (0256), b = random (0256) / / the result of the connection string var result = "rgb (" + r + "," + g + "," + b + ")"; / / returns the result return result;}
Example 3: get random CAPTCHA
Function createCode () {/ / first default code is the empty string var code =''; / / set the length. Depending on the requirements here, I set 4 var codeLength = 4 here. / / set random characters var random = new Array (0Power1, 2pyrr3, 4, 5, 6, 8, 9, 5, 7, 8, 9, 5, 7, 8, 9, 9, 6, 7, 8, 9, 4, 5, 6, 8, 9, 5, 6, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 5, 8, 9, 6, 7, 8, 9, 9, 6, 7, 8, 9, 4, 4, 4, 7, 8, 9, 6, 7, 8, 9, 6, 7, 4, 4, 4, 4, 4, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 7, 7, 8, 9 'Z') / / Loop codeLength 4 is to cycle 4 times for (var I = 0; I < codeLength; iTunes +) {/ / set the range of random numbers to 0-36 var index = Math.floor (Math.random () * 36); / / string concatenation will concatenate each random character code + = random [index] } / / assign the concatenated string to the displayed Value return code} so far, I believe you have a deeper understanding of "which commonly used objects in JavaScript", you might as well do some actual operation! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.