The 13 most common JavaScript errors -- convert

Source: Internet
Author: User
Tags integer numbers

Original article address:13 most common JavaScript errors

 

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 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(); 

 

7. Differences between integer numbers and floating-point numbers differentiate float numbers from integer numbers

Example:

 
 
  1. var myNumber = 3.5;  
  2. var myResult = 3.5 + 1.0; //We use .0 to keep the result as float 

In JavaScript, there is no difference between floating point and integer. In fact, every number in Javascript indicates that the dual-precision 64-bit format IEEE 754 is used. In short, all numbers are floating points.

Solution: Do not use decimals to convert numbers (numbers) to floating points (floats ).

 
 
  1. var myNumber = 3.5;  
  2. var myResult = 3.5 + 1; //Result is 4.5, as expected 

8. Use with () as a shortcut usage of with () as a shortcut cut

Example:

 
 
  1. team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};  
  2. with (team.attackers.myWarrior){  
  3.     console.log ( “Your warrior power is ” + (attack * speed));  

Before discussing with (), you must understand how JavaScript contexts works. Each function has an execution context (statement). In short, it includes all the variables that can be accessed by the function. Therefore, context contains arguments and definition variables.

What is with () actually? Is to insert an object to the context chain, which is embedded between the current context and the parent context. As you can see, the with () shortcut will be very slow.

Solution: Do not use with () for shortcuts. Only for context injection.

 
 
  1. team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};  
  2. var sc = team.attackers.myWarrior;  
  3. console.log(“Your warrior power is ” + (sc.attack * sc.speed)); 

9. setTimeout/setinterval string usage of strings with setTimeout/setinterval

Example:

 
 
  1. function log1() { console.log(document.location); }  
  2. function log2(arg) { console.log(arg); }  
  3. var myValue = “test”;  
  4. setTimeout(“log1()”, 100);  
  5. setTimeout(“log2(” + myValue + “)”, 200); 

SetTimeout () and setinterval () can be either a function or a string as the first parameter. If you pass a string, the engine will create a new function (using the function constructor), which will be very slow in some browsers. Instead, the function itself is passed as the first parameter, which is faster, more powerful, and cleaner.

Solution: Do not use strings for setTimeout () or setinterval ().

 
 
  1. function log1() { console.log(document.location); }  
  2. function log2(arg) { console.log(arg); }  
  3. var myValue = “test”;  
  4. setTimeout(log1, 100); //Reference to a function  
  5. setTimeout(function(){ //Get arg value using closures  
  6.     log2(arg);  
  7. }, 200); 

10. setinterval () usage of setinterval () for heavy functions

Example:

 
 
  1. function domOperations() {  
  2.     //Heavy DOM operations, takes about 300ms  
  3. }  
  4. setInterval(domOperations, 200); 

Setinterval () indicates that a function is included in the plan and executed only when no other execution is waiting in the main execution queue. The JavaScript engine only adds the next execution to the queue if no other execution is already in the queue. This may cause skipping or running two different executions without waiting for Ms between them.

Make sure that setinterval () does not consider how long it takes domoperations () to complete the task.

Solution: Avoid setinterval () and use setTimeout ()

 
 
  1. function domOperations() {  
  2.     //Heavy DOM operations, takes about 300ms  
  3.     //After all the job is done, set another timeout for 200 ms  
  4.     setTimeout(domOperations, 200);  
  5. }  
  6. setTimeout(domOperations, 200); 

11. Misuse of "this" misuse of "this'

There are no examples of this common error because it is difficult to create it for demonstration. The value of this in Javascript is significantly different from that in other languages.

This value in a function is defined as the time when the function is called, rather than the declared time. This is very important. In the following example, this in a function has different meanings.

* Regular function: myfunction ('arg1 ');

This points to the global object, wich is window for all browers.

* Method: someobject. myfunction ('arg1 ');

This points to object before the dot, someobject in this case.

* Constructor: var something = new myfunction ('arg1 ');

This points to an empty object.

* Using call ()/apply (): myfunction. Call (someobject, 'arg1 ');

This points to the object passed as first argument.

12. Usage of eval () to access dynamic attributes usage of eval () to access Dynamic Properties

Example:

 
 
  1. var myObject = { p1: 1, p2: 2, p3: 3};  
  2. var i = 2;  
  3. var myResult = eval(‘myObject.p’+i); 

The main problem is that using eval () to start a new execution statement is very slow.

Solution: Use square bracket notation instead of eval ().

 
 
  1. var myObject = { p1: 1, p2: 2, p3: 3};  
  2. var i = 2;  
  3. var myResult = myObject[“p”+i]; 

13. undefined as a variable usage of undefined as a variable

Example:

 
 
  1. if ( myVar === undefined ) {  
  2.     //Do something  

In the preceding example, undefined is actually a variable. All Javascript Engines will create the initialization Variable Window. undefined to undefined as the value. However, note that the variable is not only readable, but any other code can just change its value. It is strange to find that window. undefined has different values from undefined, but why is it risky?

Solution: Use typeof when checking for undefined items.

 
 
  1. if ( typeof myVar === “undefined” ) {  
  2.     //Do something  
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.