13 most common JavaScript errors (1)

Source: Internet
Author: User

BKJIA recommended topics:Answers to questions about JavaScript learning notes

1. for... array iteration Usage of for... in to iterate Arrays

Example:

 
 
  1. var myArray = [ “a”, “b”, “c” ];  
  2. var totalElements = myArray.length;  
  3. for (var i = 0; i < totalElements; i++) {  
  4.    console.log(myArray[i]);  

The main problem here is that "for..." in the statement cannot guarantee the Order, which means you will get different execution results. In addition, if someone adds some other UDF Array. prototype, your loop will traverse these functions repeatedly, just like the original Array items.

Solution: always use the for loop of the rule to traverse the array.

 
 
  1. var myArray = [ “a”, “b”, “c” ];  
  2. for (var i=0; i<myArray.length; i++) {  
  3.     console.log(myArray[i]);  

2. Array dimension Array dimensions

Example

 
 
  1. var myArray = new Array(10); 

There are two different problems. First, the developer tries to create an array containing 10 items, which will create an array with 10 blank slots. However, if you try to get an array, you will get the result of "undefined. In other words, the effect is like you have no memory space to save. There is no real good reason to predefine the array length.

The second problem is that the developer uses the array constructor to create an array, which is technically correct, but is slower than the literal notation.

Solution: Use text symbols to initialize the array. Do not predefine the length of the array.

 
 
  1. var myArray = []; 

3. Undefined properties

Example:

 
 
  1. var myObject = {  
  2.     someProperty: “value”,  
  3.     someOtherProperty: undefined  

The property is not defined. An element (Key 'someotherproperties' and value 'undefined') will be created in the object '.). If you traverse the array and check for existing elements, the following statements will return "undefined/undefined"

Typeof myObject ['someotherproperties'] // undefined

Typeof myObject ['unknownproperties'] // undefined

Solution: If you want to explicitly declare uninitialized attributes in the object, mark them as Null ).

 
 
  1. var myObject = {  
  2.     someProperty: “value”,  
  3.     someOtherProperty: null 

4. Misuse of Closures

Example:

 
 
  1. function(a, b, c) {  
  2.     var d = 10;  
  3.     var element = document.getElementById(‘myID’);  
  4.     element.onclick = (function(a, b, c, d) {  
  5.         return function() {  
  6.             alert (a + b + c + d);  
  7.         }  
  8.     })(a, b, c, d);  

Here, the developer uses two functions to pass parameters a, B, and c to onclick handler. Double functions are not required at all, increasing the complexity of the Code.

Variable abc has been defined in local functions because they have been declared as parameters in the main function. Any function in a local function can create the closure of all variables defined in the main function. Therefore, you do not need to pass them again.

Solution: Use a closed loop to simplify your code.

 
 
  1. function (a, b, c) {  
  2.     var d = 10;  
  3.     var element = document.getElementById(‘myID’);  
  4.     element.onclick = function() {  
  5.         //a, b, and c come from the outer function arguments.  
  6.         //d come from the outer function variable declarations.  
  7.         //and all of them are in my closure  
  8.         alert (a + b + c + d);  
  9. };  

5. Closures in loops

Example:

 
 
  1. var elements = document.getElementByTagName(‘div’);  
  2. for (var i = 0; i<elements.length; i++) {  
  3.     elements[i].onclick = function() {  
  4.         alert(“Div number “ + i);  
  5.     }  

In this example, when users click different divs, we want to trigger an action ("Div number 1", "Div number 2 "... ). However, if you have 10 divs on the page, all of them will display "Div number 10 ".

The problem is that when we use a local function to create a closure, the code in the function can access variable I. The key is that function I and function external I involve the same variables. When our loop ends, I points to the value 10, so the value of I in the local function will be 10.

Solution: Use the second function to pass the correct value.

 
 
  1. var elements = document.getElementsByTagName(‘div’);  
  2. for (var i = 0; i<elements.length; i++) {  
  3.     elements[i].onclick = (function(idx) { //Outer function  
  4.         return function() { //Inner function  
  5.             alert(“Div number “ + idx);  
  6.         }  
  7.     })(i);  

6. DOM object internal test leakage Memory leaks with DOM objects

Example:

 
 
  1. function attachEvents() {  
  2.     var element = document.getElementById(‘myID’);  
  3.     element.onclick = function() {  
  4.         alert(“Element clicked”);  
  5.     }  
  6. };  
  7. attachEvents(); 

This Code creates a reference loop. The variable element contains the reference of the function (To The onclick attribute ). At the same time, the function maintains a reference to the DOM element (prompting the function to access the element because of the closure .). Therefore, JavaScript Garbage Collectors cannot clear elements or functions because they are referenced by each other. Most JavaScript Engines are not smart enough to clear loop applications.

Solution: Avoid the closures or avoid circular references in the function.

 
 
  1. function attachEvents() {  
  2.     var element = document.getElementById(‘myID’);  
  3.     element.onclick = function() {  
  4.         //Remove element, so function can be collected by GC  
  5.         delete element;  
  6.         alert(“Element clicked”);  
  7.     }  
  8. };  
  9. attachEvents(); 


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.