JavaScript objects and inheritance tutorial built-in objects (1)

Source: Internet
Author: User
Tags anonymous array arrays object functions sort variable tostring

I. Classes and objects

In the JavaScript world, the first concept to be clarified about object-oriented is the class. objects are defined by a class, and creating objects by class is a familiar instantiation. However, there is no real class in JavaScript, and the object is defined as the object itself. and ECMA-262 simply referred to this compromise as a conciliatory agent for the object. To facilitate understanding, I usually refer to this as a class of harmonic agents that play the role of a class.

Second, built-in objects

1, Array class

Array in JS is very commonly used in a data structure, because of its flexibility and ease of use, the rational usage of arrays can help us to better implement the corresponding functions.

Let's look at the creation of the Array object first.

First type:

 
  
  
  1. var arr = new Array (10);

This method is not so practical in the actual use, and many compiler languages, the length of JS array is variable, not only enhance the flexibility, we have more good choices.

The second type:

 
  
  
  1. var arr = new Array ("One", "two", "three");

The way to create an array using the new method is generally more of both, but you can also use the new array () to create an empty array object. In general, I recommend the following methods

The third type:

 
  
  
  1. var arr = ["One", "two", "three"];

Creating an Array object using the literal form of an array is not only simple and readable, but is almost entirely equivalent to the effect of creating an array object using the new method. There are a lot of useful methods for array objects, so let's take a look at the powerful features of this array object.

The first thing to introduce is the push method, and the friends who have studied the data structure know what push means, and yes, his presence allows the array to implement the stack's data structure (and need to match the pop method). The push method helps us to add an array element in a compact way. The previous mention of the array in JS is variable in length, then we can add elements. Since can pass arr[length] = newvalue; To add a new element to the ARR and place it at the end of the array. A better approach would be to use the push method. Arr.push (NewValue); Well, it's more convenient to use him than you are to assign new values to the length of the array. Here's one thing to be aware of. Take a look at the following code:

 
  
  
  1. var arr = [];
  2. ARR[4] = 5;
  3. Alert (arr.length = 5);
  4. Alert (arr); Alert:,,,, 5

This assignment is useful when we need to assign a specified value to the specified array position, such as when it is used in a boxed sort.

The Pop method is to implement the opposite of the push, returning the last element of the array and out of the stack.

 
  
  
  1. var arr = [1,2,3,4,5];
  2. var ele = Arr.pop ();
  3. Alert (ele = 5);
  4. Alert (arr.length = 4);

The ToString and ValueOf methods of array objects are rewritten in a humane way, and its implementation is to call each item the ToString method and then concatenate each item with a half-width comma (,). So:

 
  
  
  1. var arr = [1,2,3,4,5];
  2. Alert (arr);//output:1,2,3,4,5

The toLocaleString method does not elaborate here, and his effect is similar to the ToString method, except that each call to the Tolocatestring method.

If you want to use the personalized separator to display array elements, then the join method may be more appropriate. Like what:

 
  
  
  1. var city = ["Shanghai", "Beijing", "Tianjin", "Chongqing", "Shenzhen"];
  2. Alert (City.join (""));//output: Shanghai, Beijing, Tianjin, Chongqing, Shenzhen

This shows that the join is converting an array element to a string. We will see the use of the Join method again when we introduce the string.

The concat method and the slice method are another handy method, and the special thing about these two methods is that the String object also owns them. When we want to add multiple array elements to an array, using the push may seem redundant and complicated, and it makes coding less interesting. Fortunately, we have the Concat method, which joins its parameters in the array element in sequence. Such as:

 
  
  
  1. var arr = [1,2,3,4,5];
  2. arr = Arr.concat (6,7,8,9);
  3. Alert (arr.length = 9);

Note that concat does not modify the array object itself, but instead merges the array elements with the array elements of the concat method and returns. Therefore, the array elements need to be assigned to the operation of the line.

The slice method returns a child array from the array object. The child array is the position indicated by the first argument of the slice method to the second parameter. This is a half-open half-closed interval [a,b]. Such as:

 
  
  
  1. var arr = [1,2,3,4,5];
  2. var arr1 = Arr.slice (1,3);
  3. alert (ARR1); output:2,3
  4. Alert (arr); output:1,2,3,4,5

Well, the slice and concat methods are not the same as modifying the array object itself. At the same time, the parameter 1,3 represents the sub array of the Half-open half-closed interval from position 1 to position 3.

We've just discussed the LIFO stack operation, so let's take a look at the FIFO queue operation. The push method is not a problem in the column. Is shift, he deletes the first element of an array object and returns:

 
  
  
  1. var arr = [1,2,3,4,5];
  2. var ele = Arr.shift ();
  3. alert (ele); Output:1
  4. alert (arr.length);//output:4

Another method, called Unshift, inserts the new element into the first item of the array object, and the function is the opposite of the shift.

The

Sort method is flexible and well used, and he can sort the array elements in any sort of way you want. Because the sort method receives an anonymous function (in fact, it can also receive a function that is not anonymous, but it is not usually recommended to create one such named function unless the function is reusable) as a condition of its own sort. For example,

 
  
  
  1. object.prototype.tostring = function () {   
  2. var str =  ';   
  3. for (var item in this)  {   
  4. str += item +  ":  + this[item] + ", ";   
  5. Li class= "alt" >}   
  6. return str.length?str.substr (0,str.length-1):str;   
  7. };   
  8. var arr = [{key:3,value: "Three"},  
  9. arr.sort (function (a,b) {   
  10. return a.key - b.key;   
  11. });   
  12. alert (arr) ;  
  13. //output:key:1,value:one,key:2,value:two,key:3,value:three   

Let's not go to the tangle Object.prototype.toString method, his left and right is to pass the object traversal so that it can be output as a key-value pair of format strings, in the introduction of the prototype chain will be mentioned again. We can see that the sort method allows us to sort by the key attribute through this anonymous method. So let's take a look at this anonymous method.

 
  
  
  1. function (a,b) {
  2. return a.key-b.key;
  3. };

As you can see, this method receives 2 parameters and then compares itself or a property of the parameter, and then returns the results of the comparison, and their comparison to the sort corresponds to the following:

If Parama-paramb > 0,return positive, B is in front of a

If Parama-paramb < 0,return negative, B is ranked after a

If Parama-paramb = 0,return 0, the order is unchanged.

The above implementation is sequential sort, then reverse? Yes, return Paramb-parama;

The reverse method can reverse an array object. Like the sort method, he modifies the order of elements within an array object.

Finally, let's look at the splice method, which is the way to replace and delete an array object element. Depending on the parameters of the change and have different implementation results. Splice (Pos,count[,insertparams]);p OS parameter is the location of the first item to delete the element, the count parameter is the number of deleted elements, and when 0 is not deleted (do not delete the method why, don't worry, look down), Insertparams is the list of parameters, which are the collection of elements that are about to be inserted. The location of the insertion is POS. Then there are the following situations.

1, when Insertparams ignored, this method is to delete the array elements

2, when the count parameter is 0 o'clock, the method will simply insert Insertparams into the POS location

3. When the count parameter is not 0 and Insertparams is not ignored, the method is to delete the Count element at the beginning of the POS position and replace the Insertparams parameter collection.

2. Math class

We took a lot of space to introduce the array class, and I would like to stress again that this class is simply a name for the convenience imposed on it, and that they are simply objects. Rather than the real class.

The use of the math class is relatively narrow because he is a mathematical computing class, not a data structure class, but we also see Math.random and various methods of rounding. So we might as well take some time to look at them, but if you're not interested in that, then you can skip to the next section after reading the random method, and then flip the manual later.

Math is usually a "static" class, because no one will instantiate a math object, but instead use its "static" method directly, some of which refer directly to the Math object, where we might call it a "static" class.

First I have to introduce the random method, because he is used and very useful. He is always indispensable in making random events, and he also seems to be useful in preventing caching. The Math.random method returns an open interval floating-point number between 0 and 1. That is (0,1), his use is very simple, the only thing to note is that when we take the whole of the floor and Ceil methods to filter the need for caution, the former makes random indirectly converted to the front closed after the open interval, and The latter is the anterior open posterior closure interval. If we now need a random number of 1-100, then there are two common solutions

Method One:

 
  
  
  1. Math.ceil (math.random*100);

Method Two:

 
  
  
  1. Math.floor (math.random*100) +1;

The Ceil method and the floor method are all mathematical methods for rounding, which we can understand by means of the word meaning, the former being rounded up and the latter being rounded down.

When we randomly select an array element from a contiguous array object, we can use random to easily help us pick:

 
  
  
  1. ["ipad", "iphone", "ipod Touch", "ipod nano", "MacBook"]
  2. [Math.ceil (Math.random () *4)];

In this example, I'm using the literal volume of the array directly, at first you may find it confusing or difficult to understand, and when you go deep you will find that JavaScript is so convenient, concise, and flexible.

We introduced the ceil and floor methods, so when we want to get close to the house, we can use the Math.Round method, which is close to rounding according to the value when rounding. For example, Math.Round (5.4) returns 5. So if Math.Round (5.5), the answer is 6 instead of 5. There needs to be some understanding of this. Well, I admit I'm serious, but I know what's bad about him.

What do we do when we want to get a smaller or larger number from 2 numbers?

 
  
  
  1. if (a>b) {
  2. return A;
  3. } else {
  4. return b;
  5. }

We are so paranoid. Math provides Math.max and Math.min methods to help us solve this problem.

Math also has a whole bunch of "static" methods and properties. Here I will not enumerate, when we want to do mathematical calculations, we might as well look up the manual.

3. String class

String objects are more likely to be used than array objects, why should I put them in the back, in fact because we have more to say for strings, and extensible methods and tool functions are richer. Let's take a look at the String class itself.

There are several ways to create a string object:

Method One:

 
  
  
  1. var str = new String ("Hello World");

Method Two:

 
  
  
  1. var str = String ("Hello World");

Method Three:

 
  
  
  1. var str = "Hello world";

As with arrays of objects, I recommend the last method, and the literal number of strings. There is a very detailed explanation for the difference between new and Zhou's blog, and if you keep reading, you'll also mention the new operator when you introduce the custom object.

The string object has only one attribute length, and he returns the length of the string, where we have to understand that JavaScript is Unicode encoding, and that both Chinese and English are treated as a character length. I mentioned this because I have met more than one friend in the forum to ask this question, oh, the necessity of doing. So what if we have to count the characters as 2 characters long? This brings us to our first custom method.

 
  
  
  1. String.prototype.getLength = function (issplit) {
  2. if (issplit) {
  3. Return This.replace (/[^\u0000-\u00ff]/g, "tt"). Length;
  4. }
  5. else {
  6. return this.length;
  7. }
  8. };

This method, by passing a Boolean parameter, if it is true, divides the non half-width character, number, and English letter into 2 lengths to find the length, without worrying about the split, he does not modify the string object itself. If False, the length property value is returned directly. As the introduction method is not based on the character order of the method, if as a dictionary, I think it is more appropriate to W3school, because I am based on the difference between the role and relevance of the introduction. OK, we're done with the length property, so let's look at the string lookup.


[1] [2] Next page



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.