Seven basic points of knowledge that JavaScript developers often ignore or misuse

Source: Internet
Author: User

  English Original:7 JavaScript Basics Many developers aren ' t Using (properly)

JavaScript itself can be a simple language, but we are constantly using smart and flexible patterns to improve it. Yesterday we applied these patterns to the JAVASCRIPT framework, and today these frameworks drive our WEB applications. Many novice developers are attracted by a variety of powerful JavaScript frameworks, but they overlook the versatile JavaScript techniques behind the frame. This article will present you with 7 of these basic points of knowledge.

1. Use the/g and/I flag bits in the String.prototype.replace method

To the surprise of many JavaScript beginners, the Replace method of a string does not replace all matching substrings-only the first match. Of course, JavaScript veterans know that you can use regular expressions here, and you need to add a global flag bit (/g):

    Mistake      //stepped on the pit      var str = "David is a Arsenal fan, which means David is great";      Str.replace ("David", "Darren"); "Darren is a Arsenal fan, which means David is great"      //desired      //In line with the expected      str.replace (/david/g, "Darren"); "Darren is a Arsenal fan, which means Darren is great"  

Another basic logic error is that in case-insensitive check cases (Letters can be uppercase and lowercase) without ignoring the case, the/I flag bit is useful at this point:

Str.replace (/david/gi, "Darren"); "Darren is always being an Arsenal fan, which means Darren'll always be great"

I have not read the meaning of the above example, it may be the wrong comment ... )
Every JavaScript developer has stepped on the pits of these two flags-so don't forget to use them at the right time!

2. Class array objects and Array.prototype.slice methods

The slice method of an array is typically used to extract fragments from an array. What many developers don't understand is that this method can also be used to convert "class array" elements (such as the arguments parameter list, node list, and attribute list) to a real array: The DOM element's attribute list is obtained through the Attributes property, such as Document.body.attributes. )

    var Nodesarr = Array.prototype.slice.call (Document.queryselectorall ("div"));      "True" array of divs      //Gets a "real" array of div elements,      var Argsarr = Array.prototype.slice.call (arguments);      Changes arguments to "true" array      //convert arguments to a "real" array      you can also use a simple slice to clone an array:      var clone = Myar Ray.slice (0); Naive clone                                    //Light clone  

(Note: Here the parameter 0 can also be omitted, I estimate undefined by the slice method automatically converted to 0.) )

Array.prototype.slice is definitely a treasure in the JavaScript world, but JavaScript beginners are clearly unaware of its full potential.

3. Array.prototype.sort method

The sort method of arrays is far from being fully exploited and may be more powerful than the developers think. Many developers may feel that the sort method can be used to do this kind of thing:

    [1, 3, 9, 2].sort ();    Back to [1, 2, 3, 9]  

...... That's true, but it has more powerful uses, like this:

    [          {name: "Robin Van pursestrings", age:30},          {name: "Theo Walcott", age:24},          {name: "Bacary Sagna", Age:      ].sort (function (obj1, obj2) {          //Ascending:first age less than the previous          //implementation sequence: The former age is smaller than          return obj1.age-obj2.age;      });          Returns:            //[          //    {name: "Theo Walcott", age:24},          //    {name: "Bacary Sagna", Age:28  },          //    {name: "Robin Van pursestrings", age:30}      // ]  

You can sort objects by properties, not only for simple types of array items. If one day the server sends a piece of JSON data, and the objects in it need to be sorted, don't forget this trick!

4. Truncating an array with the Length property

Almost all developers have stepped on this hole in JavaScript--"pass the object is just a reference." Developers often try to empty an array, but in fact they create a new array in the wrong way.

    var MyArray = Yourarray = [1, 2, 3];      :(      //      myArray = [];//' Yourarray ' is still [1, 2, 3]                    //' Yourarray ' are still [1, 2, 3]      //The right-means, Keeping reference      //The correct method is to keep the reference      myarray.length = 0;//' Yourarray ' and ' MyArray ' both []                          //' Yourarray ' and ' my Array ' (and all other references to the array) becomes []  

The people in the pit finally understood that the original object was only quoted. So when I reassign the myArray to [], I do create a new empty array, but the other references to the old array remain the same! Big Hole! Let's change the method of truncation, junior.

5. Using push to merge arrays

In the 2nd section above, I've shown a few small tricks that the array slice and the Apply method can combine, so you should be prepared for the other techniques of array methods. This time we use the push method to merge the arrays:

    var mergeto = [4,5,6];      var mergefrom = [7,8,9];            Array.prototype.push.apply (mergeto, mergefrom);            MergeTo; is: [4, 5, 6, 7, 8, 9]  

This is an obscure trick, and simple native methods can be used to implement common tasks such as array merging. This method is not only clever except that the push method can receive multiple parameters, but also involves the use of the second parameter of the Apply method. )

6. Efficient detection of functional characteristics and object properties

Many times developers will explore some of the features of the browser as follows:

    if (navigator.geolocation) {          //do some stuff          //doing something here      }  

Of course it works, but it doesn't have to be very efficient. Because this object probing method initializes the resource in the browser. In the past, the code snippet above could lead to memory leaks under some browsers. A better, faster approach is to check whether an object contains a key name:

    if ("Geolocation" in navigator) {          //Does some stuff          //do something here      }  

The key name check is simple and can avoid memory leaks. Also note that if the value of this property is false, the previous probe will result in a "no" and cannot really detect if the key name exists.

7. Preventdefault and Stoppropagation methods for event objects

Many times, when an action element (such as a link) is clicked, a function is triggered. Obviously we do not want the browser to follow this link when the link is clicked, so we will habitually use the Event.stop method of the JavaScript class library:

    $ ("A.trigger"). On ("click", Function (e) {          e.stop ();          do more stuff//To do something here      });  

Do not know which class library has this method, estimated its function is equivalent to return false; it. The syntax looks like jquery, but jquery does not have this method, and jquery supports the E.preventdefault and E.stoppropagation methods. )

This lazy method has a problem that not only prevents the browser's default action, but also prevents the event from bubbling. This means that the other event listeners that are bound by the element will not be triggered because they do not know that an event has occurred at all. Use Preventdefault now!

JavaScript veteran see this article may say "I knew", but perhaps when, they will at some point on the flop. Remind everyone to notice the various small details in JavaScript, near misses great difference Ah!

Seven basic points of knowledge that JavaScript developers often ignore or misuse

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.