A brief introduction to JavaScript Objects (ii)

Source: Internet
Author: User
Tags modifier modifiers natural logarithm rounds square root javascript array

JavaScript Array (Array) object
The purpose of an array object is to use a separate variable name to store a series of values.

What is an array?
An array object uses a separate variable name to store a series of values.
If you have a set of data (for example: car name), there are separate variables as follows:
var car1= "Saab";
var car2= "Volvo";
var car3= "BMW";
However, what if you want to find a car from here? And not 3 cars, but 300 cars? It's not going to be easy!
The best way is to use arrays.
An array can store all of the values with a variable name, and any value can be accessed with a variable name.
Each element in the array has its own ID so that it can be easily accessed.

Create an array
There are three ways to create an array.
The following code defines an array object named Mycars:
1: Conventional way:
var mycars=new Array ();
Mycars[0]= "Saab";
Mycars[1]= "Volvo";
Mycars[2]= "BMW";
2: Simple way:
var mycars=new Array ("Saab", "Volvo", "BMW");
3: literally:
var mycars=["Saab", "Volvo", "BMW"];

accessing arrays
By specifying the array name and the index number, you can access a particular element.
The following instance can access the first value of the Mycars array:
var name=mycars[0];
The following instance modifies the first element of the array Mycars:
Mycars[0]= "Opel";

Lamp[0] is the first element of the array. [1] is the second element of the array.

You can have different objects in an array
All JavaScript variables are objects. An array element is an object. The function is an object.
Therefore, you can have different types of variables in the array.
You can include object elements, functions, and arrays in an array:
Myarray[0]=date.now;
Myarray[1]=myfunction;
Myarray[2]=mycars;

Array methods and properties
Pre-defined properties and methods using array objects:
The number of elements in Var x=mycars.length//Mycars
Index value of Var y=mycars.indexof ("Volvo")//"Volvo" value

Array Object
The Array object is used to store multiple values in a variable:
var cars = ["Saab", "Volvo", "BMW"];
The first array element has an index value of 0, a second index value of 1, and so on.
For more information about JavaScript array, refer to the JavaScript array object manual.
Array properties
Property Description
Constructor returns the prototype function that created the array object.
Length Sets or returns the number of array elements.
Prototype allows you to add properties or methods to an array object.
Array Object Properties
Method description
Concat () joins two or more arrays and returns the result.
Copywithin () copies the element from the specified position in the array to another specified position in the array.
Every () detects whether each element of a numeric element meets the criteria.
Fill () fills the array with a fixed value.
Filter () detects the numeric element and returns an array of all elements that match the condition.
Find () returns an array element that conforms to an incoming test (function) condition.
FindIndex () returns an array element index that conforms to the passed-in test (function) condition.
The ForEach () array executes the callback function once for each element.
IndexOf () Searches the elements in the array and returns where it is located.
Join () Places all elements of an array into a string.
LastIndexOf () returns the position of the last occurrence of a specified string value, in a string at the specified position, from the back to the forward search.
Map () Processes each element of an array by specifying a function and returns the processed array.
Pop () deletes the last element of the array and returns the deleted element.
Push () adds one or more elements to the end of the array and returns the new length.
Reduce () evaluates the array elements to a value (from left to right).
Reduceright () evaluates the array element to a value (right-to-left).
Reverse () Reverses the element order of the array.
Shift () deletes and returns the first element of the array.
Slice () selects part of the array and returns a new array.
Some () detects whether an element in an array element meets the specified criteria.
Sort () Sorts the elements of an array.
Splice () to add or remove elements from the array.
ToString () converts the array to a string and returns the result.
Unshift () adds one or more elements to the beginning of the array and returns the new length.
ValueOf () returns the original value of the array object.

Create a new method
The prototype is a JavaScript global constructor. It can build properties and methods for new JavaScript objects.
Example: Create a new method.
<script>
Array.prototype.myucase=function () {
for (i=0;i<this.length;i++) {
This[i]=this[i].touppercase ();
}
}
function MyFunction () {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Fruits.myucase ();
var X=document.getelementbyid ("demo");
X.innerhtml=fruits;
}
</script>
Instance:
A Two-level cascading menu is implemented with a two-dimensional array combined with a select object.
Select1 Provincial menu, Select2 City level menu
Add Event onchange= "AddOption ()" to the provincial label
<select id= "A1" onchange= "AddOption ()" >
<option value= "Jiangsu" > Jiangsu </option>
<option value= "Hebei" > Hebei </option>
</select>
<select id= "A2" >
<option value= "Nanjing" > Nanjing </option>
<option value= "Lianyungang" > Lianyungang </option>
<option value= "Suzhou" > Suzhou </option>
<option value= "Zhen Zhou" > Zhen Zhou </option>
</select>
var city = new Array;
city[' Jiangsu '] = [' Nanjing ', ' Lianyungang ', ' Suzhou ', ' Zhenjiang '];
city[' Hebei '] = [' Shijiazhuang ', ' Baoding ', ' Hengshui ', ' Handan ', ' Langfang '];
function allcity () {
var select1 = document.getElementById (' A1 ');
for (var i in city) {
Select1.add (New Option (i,i), null);
}
AddOption ();
}
function AddOption () {
var select2 = document.getElementById (' A2 ');
var select1 = document.getElementById (' A1 '). Value;
select2.length = 0; Empty the city menu every time.
if (select1! = ' Please select Province ') {
for (Var i in City[select1]) {
Select2.add (New Option (city[select1][i],city[select1][i]), NULL);
}
}else if (Select1 = = ' Please select Province ') {
select2.length = 0;
Select2.add (' Choose City ', ' Please select City '), null);
}
}
Window.onload = Allcity ();

JavaScript Boolean (Boolean) object
A Boolean (Boolean) object is used to convert a non-Boolean value to a Boolean value (True or false).

Checks whether the Boolean object is True or false.
<script>
var b1=new Boolean (0);
var b2=new Boolean (1);
var b3=new Boolean ("");
var b4=new Boolean (NULL);
var b5=new Boolean (NaN);
var b6=new Boolean ("false");
document.write ("0 is Boolean" + B1 + "<br>");
document.write ("1 is Boolean" + b2 + "<br>");
document.write ("Empty string is Boolean" + B3 + "<br>");
document.write ("null is Boolean" + b4+ "<br>");
document.write ("NaN is a Boolean value" + B5 + "<br>");
document.write ("String ' false ' is a Boolean value" + B6 + "<br>");
</script>

Boolean Object
The Boolean object is used to convert a value that is not a Boolean type to a Boolean value (True or false).
For a complete tutorial on the Boolean object, visit the JavaScript Boolean object tutorial.
Boolean Object Properties
Property Description
Constructor returns a reference to the Boolean function that created this object
Prototype gives you the ability to add properties and methods to objects.
Boolean Object method
Method description
ToString () converts the Boolean value to a string and returns the result.
ValueOf () returns the original value of the Boolean object.

Create a Boolean object
A Boolean object represents two values: "True" or "false"
The following code defines a Boolean object named Myboolean:
var myboolean=new Boolean ();
If the Boolean object has no initial value or its value is:
0
-0
Null
""
False
Undefined
NaN
Then the value of the object is false. Otherwise, its value is true, even when the value of the variable is the string "false"!

JavaScript Math (Arithmetic) object
The Math object works by performing common arithmetic tasks.

Instance:
Returns a random integer between 0-4
Generate a random number between 0-4
var randomnum = Math.random ();
The value after rounding is taken
y = Math.Round (randomnum);

The

Math object
Math object is used to perform mathematical tasks. The
Math object is not a class of objects like Date and String, so there is no constructor for math ().
Syntax
var x = Math.PI;//returns PI
var y = math.sqrt (16);//returns the square root of 16
Math Object Properties
Property Description
E returns arithmetic constants E, which is the base of the natural logarithm (approximately equal to 2.718). The
LN2 returns the natural logarithm of 2 (approximately equal to 0.693). The
LN10 returns the natural logarithm of 10 (approximately equal to 2.302). The
LOG2E returns the logarithm of e that is base 2 (approximately equal to 1.414). The
log10e returns the logarithm of e that is base 10 (approximately equal to 0.434). The
Pi returns PI (approximately equal to 3.14159). The
Sqrt1_2 returns the reciprocal of the square root that returns 2 (approximately equals 0.707). The
SQRT2 returns the square root of 2 (approximately equal to 1.414). The
Math Object Method
Method describes
ABS (x) returns the absolute value of x.
ACOs (x) returns the inverse cosine value of x.
ASIN (x) returns the inverse sine value of x.
Atan (x) returns the inverse tangent of x with a value between-PI/2 and PI/2 radians.
atan2 (y,x) returns the angle from the x-axis to the point (X, y) (between-PI/2 and PI/2 radians). The
Ceil (x) is rounded on the logarithm. The cosine of the
cos (x) return number.
Exp (x) returns the exponent of Ex.
Floor (x) rounds x down. The natural logarithm of the
log (x) return number (bottom is e).
Max (x, y, z,..., N) returns the highest value in X, Y, z,..., N.
min (x, y, z,..., N) returns the lowest value in X, Y, z,..., N. The
Pow (x, y) returns the y power of X. The
Random () returns a random number between 0 and 1.
Round (x) rounds the number to the nearest integer. The sine of the
sin (x) return number.
sqrt (x) returns the square root of the number.
Tan (x) returns the tangent of the corner:

The following example rounds a number by using the round method of the Math object.
document.write (Math.Round (4.7));
The above code output is:
5
The following example uses the random () method of the Math object to return an arbitrary number between 0 and 1:
document.write (Math.random ());
The above code output is:
0.5967274364885273
The following example uses the floor () method and random () of the Math object to return a random number between 0 and 11:
document.write (Math.floor (Math.random () *11));
The above code output is:
6

JavaScript REGEXP Objects
REGEXP: is a shorthand for regular expressions (regular expression).

Grammar
var patt=new RegExp (pattern,modifiers);

Or in a simpler way:

var patt=/pattern/modifiers;
Pattern (pattern) describes the mode of an expression
modifiers (modifier) for specifying global matching, case-sensitive matching, and multiline matching
Note: When you use constructors to create regular objects, you need a regular character escaping rule (preceded by a backslash \). For example, the following are equivalent:
var re = new RegExp ("\\w+");
var re =/\w+/;
For more information on REGEXP objects please read our JavaScript RegExp object tutorial.
Modifier
Modifiers are used to perform case-sensitive and global matching:
Modifier description
I perform a match on case insensitive.
G performs a global match (finds all matches rather than stops after the first match is found).
M performs multi-line matching.
Square brackets
Square brackets are used to find characters in a range:
Expression Description
[ABC] finds any character between square brackets.
[^ABC] finds any characters that are not in brackets.
[0-9] Find any number from 0 to 9.
[A-z] finds any characters from lowercase a to lower Z.
[A-z] finds any characters from uppercase A to uppercase Z.
[A-z] finds any characters from uppercase A to lowercase z.
[ADGK] finds any character within a given collection.
[^ADGK] finds any character outside the given set.
(Red|blue|green) to find any of the specified options.
Meta character
Metacharacters (metacharacter) is a character that has a special meaning:
Metacharacters description
. Finds a single character, in addition to line breaks and line terminators.
\w find word characters.
\w Find non-word characters.
\d find numbers.
\d to find non-numeric characters.
\s Find white space characters.
\s find non-whitespace characters.
\b matches the word boundary.
\b Matches a non-word boundary.
To find the NULL character.
\ nto find newline characters.
\f Find a page break.
\ r to find the carriage return character.
\ t to find a tab.
\v Find vertical tabs.
\xxx finds characters that are specified in octal number XXX.
\XDD finds the characters specified in hexadecimal number DD.
\uxxxx finds Unicode characters that are specified in hexadecimal number xxxx.
quantifier
Quantifier description
n+
Matches any string that contains at least one n.
For example,/a+/matches "a" in "Candy" and All "a" in "Caaaaaaandy".
N
Matches any string that contains 0 or more N.
For example,/bo*/matches "B" in "a Ghost booooed" in "Boooo", "A bird warbled", but does not match "a goat grunted".
N?
Matches any string that contains 0 or one n.
For example,/e?le?/matches "El" in "Angel", "le" in "angle".
N{X}
Matches a string that contains a sequence of X N.
For example,/a{2}/does not match "a" in "Candy," but matches the two "a" in "Caandy," and matches the first two "a" in "Caaandy."
N{x,}
X is a positive integer. The preceding pattern n is matched at least X times consecutively.
For example,/a{2,}/does not match "a" in "Candy", but matches all "a" in "Caandy" and "Caaaaaaandy."
N{x,y}
X and Y are positive integers. The preceding pattern n appears consecutively at least X times, and matches at most Y times.
For example,/a{1,3}/does not match "Cndy", Matches "a" in "Candy," "Caandy," in two "a", and matches the first three "a" in "Caaaaaaandy". Note that when "Caaaaaaandy" is matched, even if the original string has more "a", the match is "AAA".
n$ matches any string that ends with N.
^n matches any string that begins with N.
=n matches any string immediately following the specified string n.
?! n matches any string that does not follow the specified string n immediately thereafter.
RegExp Object Methods
Method description
Compile compile the regular expression.
EXEC retrieves the value specified in the string. Returns the found value and determines its location.
Test retrieves the value specified in the string. Returns TRUE or FALSE.
Methods for String objects that support regular expressions
Method description
Search retrieves the value that matches the regular expression.
Match finds the matching of one or more regular expressions.
Replace replaces the substring that matches the regular expression.
Split splits the string into an array of strings.

Example 1:
Find "Runoob" in strings that are case insensitive
<script>
var str = "Visit Runoob";
var patt1 =/runoob/i;
document.write (Str.match (PATT1));
</script>
Example 2:
Full text find "is"
<script>
var str= "is the There is?";
var patt1=/is/g;
document.write (Str.match (PATT1));
</script>
Example 3:
Full-text lookup and case insensitive search "is"
<script>
var str= "is the There is?";
var patt1=/is/gi;
document.write (Str.match (PATT1));
</script>

Test ()
The test () method searches for the value specified by the string, depending on the result and returns TRUE or false.
The following example searches for the character "E" from a string:
Instance
var patt1=new RegExp ("E");
document.write (Patt1.test ("The best things in life is free");
Because the letter "E" exists in the string, the output of the above code will be:
True

Regular character escaping rules (preceded by backslash \) are required when creating a regular object using a constructor function
<script>
var str = ' Runoob ';
var patt1 = new RegExp (' \\w ', ' G '); Have escaped as regular expression processing
var patt2 = new RegExp (' \w ', ' G '); No escape As String processing
var patt3 =/\w+/g; Same as PATT1 effect
document.write (Patt1.test (str))//Output True
document.write ("<br>")
document.write (Patt2.test (str))//Output False
document.write ("<br>")
document.write (Patt3.test (str))//Output True
</script>

EXEC ()
The EXEC () method retrieves the specified value in the string. The return value is the value that was found. If no match is found, NULL is returned.
The following example searches for the character "E" from a string:
Example 1
var patt1=new RegExp ("E");
document.write (Patt1.exec ("The best things in life is free");
Because the letter "E" exists in the string, the output of the above code will be:
E

A brief introduction to JavaScript Objects (ii)

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.