JavaScript Advanced Programming Learning (iv) reference types

Source: Internet
Author: User

There are also reference types in JavaScript, as in Java.

JavaScript is also commonly used for reference types that are familiar with object and array.

An object and an array, which is the most used in both the front and back-end separation development. For example, Ajax, sometimes I don't just need a parameter, such as adding a method, passing an object, the object has a property. Objects in Java can also be said to be classes. Because the class exists attributes such as human, his attributes are height, weight, name, age, gender, etc. And JS object, can also be like this, such as car, it can have brand, color, modelling and so on.

What can JS objects do? What is the difference from Java objects?

First, if you want to question what the JS object can do, the simplest and most straightforward and practical, I can put some public properties into this object, but I only need objects. property to be owned. Don't say that this is not commonly used, such as project paths, global variables, and so on. In this case, the code will get some specification. The code specification is important, and this is for beginners to keep in mind. The non-standard results in a non-stop duplication of work.

Second, the JS object is convenient for asynchronous Ajax communication, whether it is react or vue.js, I believe that the asynchronous transfer parameter is basically to use the object;

As an IT practitioner, time is money for us. Time is very valuable, because time lets us grow our knowledge ability, in this training organization numerous, the competitor numerous it circles, if one does not want to carry on doing the job other whether does not ask is very dangerous. Because that would make people comfortable. What's the most scary thing to ask programmers? Perhaps some people say, the most afraid to find the object. Others say, the most afraid of changbai hair, more people say the most afraid of sudden death in the computer. If you want to ask me, that makes sense, I can only answer is reasonable.

But in my opinion, the most feared by programmers is that there is no fighting spirit, no ambition, because the lack of these two, it can be said from now on stagnation.

Recently heard a lot of people say, do repeat things, write repetitive code, really no meaning. Indeed, the business code does not change much in that set, but what about it? And don't underestimate the business code. Business code, there are indeed duplicates. When it comes to repetition, I think of encapsulation remembering inheritance. Remember my brother said to me, when the page or several classes refer to the same code, can you think of a way? Reuse its encapsulation. Such a line of code can solve the problem of several classes of references.

What can an array do?

JS Array application scenario, combined with mybatis, you can achieve batch modification, batch distribution function.

Sometimes, for example, check box, check box, especially in the blog, such as an article, it may be a one-to-one or a lot of relationship, but the label, many-to-many relationship, multiple articles corresponding to several tags. There are examples in the blog Park itself.

Detection object or array type can use the instanceof modifier

(1) Stack method

The ECMAScript array also provides a way for the array to behave like other data structures. Specifically, an array can behave like a stack, which is a data structure that restricts the insertion and deletion of items. The stack is a LIFO (Last-in-first-out, LIFO) data structure, which means that newly added items are removed early. The insertion of the item in the stack (called Push-in) and the removal (called popup) occur only in one place-the top of the stack. The ECMAScript array specifically provides the push () and Pop () methods to implement a stack-like behavior.

<HTML><MetaCharSet= "Utf-8"><Head><Script>varColors= NewArray (); //Create an array varCount=Colors.push ("Red", "Green"); //push in two itemsalert (count); //2Count=Colors.push ("Black"); //push into another itemalert (count); //3 varItem=Colors.pop (); //get the last onealert (item); //"BLACK"alert (colors.length); //2</Script></Head><Body></Body></HTML>

(2) Queue method

The access rules for the stack data structure are LIFO (LIFO), whereas the access rules for the queue data structure are FIFO (first-in-first-out, first-in-one-out). The queue adds items at the end of the list, removing items from the front end of the list. Because push () is a method of adding items to the end of an array, it takes only one method to get an item from the front of the array to simulate the queue. The array method for doing this is shift (), which moves the first item in the array and returns the item, minus 1 of the length. Using the shift () and push () methods together, you can use arrays as you would with queues.

Examples are as follows:

var colors = new Array ();                   Create an array of var count = Colors.push ("Red", "green");    Push in two alert (count);  2  count = Colors.push ("Black");               Push into another alert (count);     3  var item = Colors.shift ();                  Get the first alert (item);      

(3) Re-order

There are already two methods in the array that can be used for reordering directly: reverse () and sort (). As the reader may have guessed, the reverse () method reverses the order of the array items

var values = [1, 2, 3, 4, 5]; Values.reverse (); alert (values);        

The sort () method can be positive, but it is usually necessary to add a function to determine

function Compare (value1, value2) {     <  value2) {         return-1;      > value2) {         return 1;     } else {         return 0;}     } var values = [0, 1, 5, ten, +]; Values.sort (compare); alert (values)   ;

(4) Operation method

ECMAScript provides a number of ways to manipulate items already contained in an array. where the concat () method can create a new array based on all the items in the current array. Specifically, this method creates a copy of the current array, adds the received parameters to the end of the copy, and returns the newly constructed array. Without passing arguments to the concat () method, it simply copies the current array and returns a copy. If one or more arrays are passed to the concat () method, the method adds each item in the array to the result array. If the value passed is not an array, the values are simply added to the end of the result array.

var colors = ["Red", "green", "blue"];var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]);  alert (colors);     Red,green,blue   alert (COLORS2);    

Slice (), which can create a new array based on one or more items in the current array. The slice () method can accept one or two parameters, that is, to return the starting and ending positions of an item. In the case of only one argument, the slice () method returns all items starting at the specified position of the parameter to the end of the current array. If there are two parameters, the method returns the item between the start and end positions--but not the end position. Note that the slice () method does not affect the original array

Example reference:

var colors = ["Red", "green", "blue", "yellow", "purple"); var colors2 = Colors.slice (1); var colors3 = Colors.slice (1,4);  alert (colors2);   Green,blue,yellow,purple alert (COLORS3);   Green,blue,yellow  



Splice () method, this method is probably a powerful array method, it has many kinds of usage. The main purpose of splice () is to insert items into the middle of the array, but there are 3 ways to use this method.

? Delete: You can delete any number of items by specifying only 2 parameters: the location of the first item to delete and the number of items to delete.

For example, splice (0,2) deletes the first two items in the array.

? Insert: You can insert any number of items to a specified location, providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert. If you want to insert more than one item, you can pass in four, five, or any number of items.

For example, splice (2,0, "Red", "green") will insert the string "red" and "green" starting at position 2 of the current array.

? Replace: You can insert any number of items at the specified location and delete any number of items at the same time by specifying 3 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,1, "Red", "green") removes the entry for the current array position 2, and then inserts the string "Red" and "green" starting at position 2. The splice () method always returns an array that contains the items that were deleted from the original array (an empty array is returned if no items were deleted).

Examples are as follows:

var colors = ["Red", "green", "blue"]; var removed = Colors.splice (0,1);                Delete the first alert (colors);     Green,blue alert (removed);    Red, the returned array contains only one item  removed = Colors.splice (1, 0, "yellow", "orange");   Insert two alert (colors) starting from position 1;     Green,yellow,orange,bluealert (removed);    Returns an empty array of  removed = Colors.splice (1, 1, "Red", "purple");      Insert two items to delete an alert (colors);     Green,red,purple,orange,blue alert (removed);    

(5) Location method

ECMAScript 5 adds two location methods to an array instance: IndexOf () and LastIndexOf (). Both methods receive two parameters: the subparagraphs (optional) to find indicates the index at which to find the starting point. where the IndexOf () method starts looking backwards from the beginning of the array (position 0), the LastIndexOf () method looks forward from the end of the array. Both of these methods return the position of the item you are looking for in the array, or return it if it is not found. 1. The equality operator is used when comparing the first argument to each item in the array, that is, the items that are required to be found must be strictly equal (as with = = =)

var numbers = [1,2,3,4,5,4,3,2,1];  Alert (Numbers.indexof (4));        3 Alert (Numbers.lastindexof (4));    5  Alert (Numbers.indexof (4, 4));     5 Alert (Numbers.lastindexof (4, 4)); 3  var person = {Name: "Nicholas"}, var people = [{name: "Nicholas"}];  var morepeople = [person];  Alert (People.indexof (person));     -1 Alert (Morepeople.indexof (person)); 0  

(6) Iterative method

ECMAScript 5 defines 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this. The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the group object itself. Depending on the method used, the return value after the function is executed may or may not affect the return value of the method. The following are the effects of these 5 iterative methods.

? Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.
? Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.

? ForEach (): Runs the given function for each item in the array. This method has no return value.

? Map (): Each item in the array runs the given function, returning an array that consists of the results of each function call.

? Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item. None of the above methods will modify the contained values in the array

var numbers = [1,2,3,4,5,4,3,2,1];  var everyresult = numbers.every (function (item, index, array) {     return (item > 2);  });  alert (everyresult);    False  var someresult = numbers.some (function (item, index, array) {     return (item > 2);});  alert (someresult);     true var numbers = [1,2,3,4,5,4,3,2,1];  var filterresult = numbers.filter (function (item, index, array) {     return (item > 2);});  alert (filterresult);  [3,4,5,4,3] var numbers = [1,2,3,4,5,4,3,2,1];  var mapresult = Numbers.map (function (item, index, array) {     return item * 2;});  alert (mapresult);  [2,4,6,8,10,8,6,4,2] var numbers = [1,2,3,4,5,4,3,2,1];  Numbers.foreach (function (item, index, array) {     //perform certain Actions  });  

(7) Merge method

ECMAScript 5 also added two methods for merging arrays: reduce () and reduceright (). Both of these methods iterate over all the items of an algebraic group and then build a value that will eventually be returned. where the reduce () method starts from the first item in the array and traverses through to the back. Reduceright () then iterates forward to the first item, starting with the last item in the array. Both methods receive two parameters: a function that is called on each item and (optionally) the initial value that is the base of the merge. The functions passed to reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second is the second item of the array.

You can use the reduce () method to perform an operation that evaluates the sum of all the values in the array, such as:

var values = [1,2,3,4,5]; var sum = values.reduce (function (prev, cur, index, array) {     return prev + cur;  }); alert (sum);//15  

The first time the callback function is executed, Prev is 1,cur is 2. The second time, Prev is 3 (1 plus 2 results), Cur is 3 (the third item in the array). This process continues until each item in the array is accessed again, and the result is returned. Reduceright () acts similarly, except in the opposite direction.

var values = [1,2,3,4,5]; var sum = values.reduceright (function (prev, cur, index, array) {     

Summary of the above examples and concepts from the "JavaScript Advanced Programming Third Edition" This book, I think his concept and examples are typical, worthy of reference and reference, so reference. I think since it is the system to learn to read this book, not only quoted, but also to their own experience, or plagiarism and what is the difference? I believe the author's intention is to allow programmers to better use JS to achieve the best results of web development.

Frankly speaking of the above methods, I have not used in the actual development, but I think it is very useful, why? In the actual development, in order to efficiency often we find ourselves most familiar with the most commonly used, when these can solve the problem, we will not consider other. So naturally the above uses little or No. There is another reason commonly used, we know its usual error probability, or after running, what effect, we are all clear, because the common reason, but not used and useless, and sometimes need to use the browser constantly debugging for a long time to find the reason. It's like, why a lot of people would rather use mybatis to write their own SQL and code, and do not want to use MyBatis plus or jeesite, because of a lot of risk is not controllable. Risk control is a very important thing for a project.

In addition to the above code, although it is borrowed from the book, but I strongly suggest that friends, when studying or reading the article, or to hold the concept of "knowledge of the line of Oneness". Every reading of a small piece, to be practiced. This is also a pleasure.

JavaScript Advanced Programming Learning (iv) reference types

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.