JavaScript Learning Summary-Object-oriented-(v)

Source: Internet
Author: User
Tags array definition

1. Object-oriented

JavaScript Object-oriented scripting language, where developers need to look for objects when they develop, and provide built-in objects by default. You can also define your own objects according to the needs of the developer.

1.1. Basic data Type wrapper class

To facilitate operation of the base type value, ECMAScript provides 3 special reference types: boolean,number,string. They are reference types. When reading the base data type, a corresponding basic wrapper class object is created in the background, so we can invoke some methods directly when we manipulate the basic data types.

1.1.1. String

Create a String object by constructor var B = new String ("Java"), var c = new String ("Java");d Ocument.write (b + "," + C);d Ocument.write (b = = C );//false//compares the values of strings for equality document.write (b.valueof () = = C.valueof ());

A common approach:

Anchor () Production anchor point

Blink () Adding Blink tags to elements

CharAt () returns the character at the specified index position.

charCodeAt () returns an Integer that represents the Unicode encoding of the character at the specified position.

Concat () returns a string value that contains the connection of two or more supplied strings.

FontColor () places an HTML <FONT> tag with a COLOR attribute on both ends of the text in a String object

IndexOf () returns the character position of the first occurrence of a substring within a string object

Italics () places the HTML <I> tag at both ends of the text in a String object.

Link () places an HTML anchor with an HREF attribute on both ends of the text in a String object.

Replace () returns the copy of the string after the literal substitution based on the regular expression

Split () cut

SUBSTR () intercept sub-string

toUpperCase () Turn capital

toLowerCase () Turn lowercase

Method Document.Write ("fifth chapter". Anchor ("CH1"));d Ocument.write ("fifth chapter". Blink ());//    returns the character at the specified position. document.write ("fifth chapter". CharAt (0));d ocument.write ("a". charCodeAt (0));d Ocument.write ("fifth chapter". Concat ("abc")); document.write ("fifth chapter". FontColor ("#ff0000"));d Ocument.write ("chapter fifth". IndexOf ("five"));d Ocument.write ("fifth chapter". italics ()); document.write ("fifth chapter". Link ());d ocument.write ("HelloWorld". Replace (/l/g, "L"));d ocument.write ("<br/>"); var names = "Jack-lili-lucy". Split ("-"); for (var temp in names) {   document.write (Names[temp] + "<br/>");} document.write ("<br/>");d ocument.write ("HelloWorld". substr (1, 2)); Eldocument.write ("HelloWorld". Substring (1, 2));//edocument.write ("HelloWorld". toUpperCase ());d Ocument.write ( New String ("Java"). ToString () = = new String ("Java"). ToString ());
1.1.2. Number

constructor function

The number object is created var a = 12;var B = new;d Ocument.write (A + ":" + b);//Comparative value truedocument.write (A = = B);//No Transformation FALSEDOCU Ment.write (A = = B);//falsedocument.write (New number = = new number)//falsedocument.write (new number (12) = = = New number);//Falsedocument.write (new number). ValueOf () = = new Number (n). ValueOf ());//truedocument.write ( New number. valueOf () = = = new Number (n). ValueOf ());

  

Property:

document.write ("Max" + Number.MAX_VALUE + "</br>");d ocument.write ("min" + number.min_value + "</br>");

Method

Method document.write (new number), ToString (+ "<br/>");d Ocument.write (new number). ToString (2) + "<br/ > ");d ocument.write (new number), ToString (8) +" <br/> ");d Ocument.write (new number). ToString +" < Br/> ");d Ocument.write (new number (12.12345) +" <br/> ");d Ocument.write (new number (12.12345). toFixed () +" < Br/> ");d Ocument.write (new number (12.12345). toFixed (2) +" <br/> ");d Ocument.write (new number (12.12345). ToFixed (3) + "<br/>");

Note: toFixed () is a specified number of decimal digits.

1.2. Math class

Methods in the Math tool class

Max ()

Min ()

Random ()

... See more documents

document.write (Math.ceil (12.34) + "<br/>")//13document.write (Math.floor (12.34) + "<br/>");// 12document.write (Math.Round (12.54) + "<br/>")//13document.write (Math.Round (12.35) + "<br/>");// 12document.write (Math.random () + "<br/>")//0~1document.write (Math.max (1, +, +) + </br> ");d Ocument.write (math.min (1, +, +) +" </br> ");
1.3. Date Object

SetInterval (code, number of milliseconds) executes the specified code after each specified millisecond value.

SetTimeout (code, number of milliseconds) executes the specified code (once only) after the specified millisecond value.

Other ways to view document learning date

function Showdate () {   //Get system time   var date = new Date ();   Get the month/day time of the second   var str = date.getfullyear () + "year" + (Date.getmonth () + 1) + "Moon" + date.getdate () + "Day" + "Week" + date.get Day () + "" + date.gethours () + "when" + date.getminutes () + "min" + date.getminutes () + "min" + date.getseconds () + "seconds"   // A good time is displayed in the leaf span label Body   var span = document.getElementById ("mydate");   Set the label body content for the span tag   span.innerhtml = Str.fontcolor ("red");   Call a timed function   

1.4. Arrays

Array definition:

There are 2 basic ways to create an array.

The first is to use the constructor of the array

Do not specify a length

    var arrs=new Array ();

If you are sure that you know the number of arrays saved, you can pass the length of the array through the constructor

Specify length

        var arrs=new Array (20);

The array has 20 elements, and the default value for each item is undefined

Specifying elements

        var arrs=new Array ("Hello"); An array of elements is created.

The second way

Specifying elements

Create an array with 3 strings

        var arrs=["AA", "BB", "CC"];

Create an empty array

        var arrs=[];        var values=[1,2];

Array initialization

       var arrs=["AA", "BB", "CC"];       Color[2]= "XX";//Modify the 3rd item       color[3]= "ZZ";//Add 4th

Array Traversal:

       for (var i = 0; i < arr.length; i++) {           alert (arr[i]);       }  

Or

       for (var i in arr) {           //I is the index in the traversed array, starting at 0, up to the maximum index.           //If there are other attributes, they are also traversed, in fact the index is the property of the array object.           alert (arr[i]);       }

Attention:

JS arrays can grow dynamically:

Array Declaration and initialization, note: The length of the array depends on the number of integers subscript var arr = new Array (); arr[0] = "AA"; 2arr[1] = "BB"; arr[6] = ' xx ';d ocument.write (arr + "<b R/> ");//traversal array for (var i = 0; i < arr.length; i++) {   document.write (arr[i]+" <br/> ");} When subscript is out of bounds: var arr = ["AA", "BB"];d ocument.write (arr[200]);//Display undefined

Common methods

Methods in the array:

Sort ()

Sorts the current array and returns the array object that has been sorted.

New objects are not created and are sorted directly in the specified array.

Reverse ()

Reverses the current array, returning an array object whose element order is reversed.

New objects are not created and are sorted directly in the specified array.

Push ([Item1 [item2] [... [Itemn]] )

These elements are added in the order in which the new elements appear.

If one of the parameters is an array, it is added as a single element to the array.

Pop ()

Moves the last element in the array and returns the element.

If the array is empty, then the undefined is returned.

Shift ()

Moves the first element in an array and returns the element.

If the array is empty, then the undefined is returned.

Unshift ([item1[, item2 [, ...] [, Itemn]]])

Inserts the specified element into the starting position of the array and returns the array.

Splice (Start, DeleteCount, [item1[, item2[, ... [, Itemn]]])

Removes the specified number of elements starting at the start position and inserts a new element, modifying the concat ([item1[, item2[, ... [, Itemn]]])

Returns a new array, which is a combination of two or more arrays. The original array does not change.

Items to add (item1 ... itemn) are added to the array in left-to-right order.

If an item is an array, then add its contents to the end of the array1.

If the item is not an array, it is added to the end of the array as a single array element.

Slice (start, [end])

Returns an array that contains the specified partial element.

Returns a segment of the index greater than or equal to start and less than end.

The original array does not change.

Join (separator)

Separates all elements from the specified delimiter to form a string that returns the string value.

If there are elements in the array that are not defined or are null, it is treated as an empty string.

var a = [1, 2, 3];//    joins two or more arrays, and returns the result. document.write (A.concat ([+]) + "<br/>");d Ocument.write (A.concat ([+], [[+]] + "<br/>");//    put all the elements of the array into a string. element is delimited by the specified delimiter. var B = A.join ("$");d Ocument.write (b + "<br/>");d Ocument.write (typeof B + "<br/>");//string//    Delete and return the last element of the array document.write (A.pop () + "<br/>");//    add one or more elements to the end of the array and return the new length. document.write (A.push) + "<br/>");//    convert the array to a string and return the result. document.write (a.tostring () + "<br/>");//Returns the original value of the array object var c = a.valueof ();d Ocument.write (typeof C + "<br/>");

Sort:

var a = [9, 3, 7,];d Ocument.write (A + "<br/>");//If the method is called without parameters, the elements in the array are sorted alphabetically a.sort (); document.write (A + "<br/>");//Specify comparison mode A.sort (CompareTo);d Ocument.write (A + "<br/>"), function CompareTo (A, b) {return a-a   ;}
1.5. Custom Object 1.5.1. No parameter constructor

/* * Custom Object * *  */function person () {   Window.document.write ("constructor () <br>"),} var person = new Person () ;//define Property Person.name = "Jack";p Erson.age = 23;//Define Method person.work = function () {   
1.5.2. Parametric constructors
function person (name, age) {   this.name = name;   This.age = age;   This.work = function () {      alert (this.name + ":" + this.age);   
1.5.3. Object mode
/* * Custom Object Mode * *  */var person = new Object ();p erson.name = "Jack";p erson.age = 28;person.sayhello = function () {   document.write (this.name + ":" + This.age);} Person.sayhello ();

This example creates an object named person and adds 2 attributes (name age) and a method (SayHello)

To create an object using the constructor mode:

The first custom class, in fact, is to define a function that is the same as the class name.

Then use the new keyword to invoke the defined class.

(any function, as long as it is called by the new operator, it can be used as a constructor)

Description

To assign a property and method to this, that is the property of the object, and if write Var str is a local variable in the method.

Do not write new Object ().

Do not write a return statement.

JS will do the following in New person ():

1, create a new object.

2,this points to the new object.

3, execute the code in the constructor method.

4, returns the new object.

Create objects by literal means:

var person={   Name: "John Doe",   age:88,   eat:function () {      alert ("Eating ...");   }}; Alert (person.name+person.age);p erson.eat ();
1.6.prototype

"Prototype" literal translation is "prototype", is the main means of javascript implementation of inheritance. Roughly speaking: prototype is a reserved property of a function in JavaScript, and its value is an object (we can call this object "prototype object").

Prototype Note the details:

    1. Prototype is a required property of a function (the written point is "reserved attribute") (as long as it is functions, there must be a prototype attribute)
    2. The value of prototype is an object
    3. You can modify the value of the prototype property of a function arbitrarily.
    4. An object automatically owns the prototype member properties and methods of the constructor for this object.

Demand:

A tool class that customizes an array.

function Arrtool () {}var arraytool = new Arrtool ();       Arraytool.getmax = function (arr) {var max = 0;    for (var x=1; x<arr.length; x + +) {if (Arr[x]>arr[max]) max = x; } return Arr[max];};       Arraytool.getmin = function (arr) {var min = arr[0];    for (var x=1; x<arr.length; x + +) {if (arr[x]<min) min = arr[x]; } return min;} /*arraytool.getmax = getmax;//Gets the maximum value.       function Getmax (arr) {var max = 0;    for (var x=1; x<arr.length; x + +) {if (Arr[x]>arr[max]) max = x; } return Arr[max];}       */arraytool.binarysearch = function (Arr,key) {var min,max,mid;    min = 0;       max = arr.length-1;             while (Min<=max) {mid = (Min+max) >>1;       if (Key>arr[mid]) min = mid + 1;       else if (Key<arr[mid]) max = mid-1;    else return mid; } return-1;} /*arraytool.binarysearch = halfsearch;//binary lookup, must be an ordered array.  function Halfsearch (arr,key) {  var Min,max,mid;    min = 0;       max = arr.length-1;             while (Min<=max) {mid = (Min+max) >>1;       if (Key>arr[mid]) min = mid + 1;       else if (Key<arr[mid]) max = mid-1;    else return mid; } return-1;}

Add the tool method of the array to the JavaScript built-in object array.

    Array.prototype.getIndex = function (Element) {for    (var x=0; x<this.length; x + +)    {       if (this[x]==element )           return x;    }    return-1;} Array.prototype.getMin = function () {    var min = this[0];    for (var x=1; x<this.length;x++)    {       if (this[x]<min)           min = this[x];    }    return min;}

Add a new method to a string

JavaScript document//adds new functionality to string strings. Removes spaces at both ends of the string. String.prototype.trim = function () {    var start,end;    start = 0;    end = This.length-1;       while (Start<=end && this.charat (start) = = "")       start++;          while (Start<=end && this.charat (end) = = ")       end--;          Return this.substring (start,end+1);} Converts a string into an array. String.prototype.toCharArray = function () {    var arr = new Array (this.length);       for (var x=0; x<this.length; x + +)    {       arr[x] = This.charat (x);    }       return arr;} Reverses the string. String.prototype.reverseString = function () {    var arr = This.tochararray ();         Return Arr.reverse (). Join ("");

JavaScript Learning Summary-Object-oriented-(v)

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.