13 most common JavaScript errors

Source: Internet
Author: User
Tags integer numbers

The most common JavaScript error is 13. You may have to make these mistakes. We describe these bad habits and come up with solutions to help developers.

1. For... array iteration usage of for... in to iterate Arrays


  1. VaRMyarray = ["A", "B", "C"];
  2. VaRTotalelements = myarray. length;
  3. For(VaRI = 0; I <totalelements; I ++ ){
  4. Console. Log (myarray [I]);
  5. }

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. VaRMyarray = ["A", "B", "C"];
  2. For(VaRI = 0; I <myarray. length; I ++ ){
  3. Console. Log (myarray [I]);
  4. }

2. array dimension array dimensions


  1. VaRMyarray =NewArray (10 );

The second problem is that the developer uses the array constructor to create arrays, which is technically correct. However, it will be slower than the literal notation. Solution: Use text symbols to initialize arrays, do not predefine the length of the array.

  1. VaRMyarray = [];

3. undefined Properties


  1. VaRMyobject = {
  2. Someproperty: "value ",
  3. Someotherproperty: Undefined
  4. }

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"

  1. TypeofMyobject ['Someotherproperties']// Undefined 
  2. TypeofMyobject ['Unknownproperties']// Undefined 

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

  1. VaRMyobject = {
  2. Someproperty: "value ",
  3. Someotherproperty:Null
  4. }

4. Misuse of closures misuse of closures


  1. Function(A, B, C ){
  2. VaRD = 10;
  3. VaRElement = 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 );
  9. }

Here, the developer uses two functions to pass parameters A, B, and C to onclick handler. Dual functions are not required at all.CodeComplexity.

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.

Take a look at the Javascript closures FAQ to learn more.

Solution: Use a closed loop to simplify your code.

  1. Function(A, B, C ){
  2. VaRD = 10;
  3. VaRElement = 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. };
  10. }

5. closures in Loops


  1. VaRElements = Document. getelementbytagname ('div ');
  2. For(VaRI = 0; I <elements. length; I ++ ){
  3. Elements [I]. onclick =Function(){
  4. Alert ("Div number" + I );
  5. }
  6. }

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. VaRElements = Document. getelementsbytagname ('div ');
  2. For(VaRI = 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 );
  8. }

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


  1. FunctionAttachevents (){
  2. VaRElement = 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


  1. VaRMynumber = 3.5;
  2. VaRMyresult = 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. VaRMynumber = 3.5;
  2. VaRMyresult = 3.5 + 1;// Result is 4.5, as expected 

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


  1. Team. Attackers. mywarrior = {attack: 1, speed: 3, Magic: 5 };
  2. With(Team. Attackers. mywarrior ){
  3. Console. Log ("your warrior power is" + (attack * speed ));
  4. }

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. VaRSC = team. Attackers. mywarrior;
  3. Console. Log ("your warrior power is" + (SC. Attack * SC. Speed ));

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


  1. FunctionLog1 () {console. Log (document. Location );}
  2. FunctionLog2 (ARG) {console. Log (ARG );}
  3. VaRMyvalue = "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


  1. FunctionDomoperations (){
  2. // Heavy Dom operations, takes about 300 ms 
  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. FunctionDomoperations (){
  2. // Heavy Dom operations, takes about 300 ms 
  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 'eas'

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


  1. VaRMyobject = {p1: 1, P2: 2, P3: 3 };
  2. VaRI = 2;
  3. VaRMyresult = 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. VaRMyobject = {p1: 1, P2: 2, P3: 3 };
  2. VaRI = 2;
  3. VaRMyresult = myobject ["p" + I];

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


  1. If(Myvar === undefined ){
  2. // Do something 
  3. }

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(TypeofMyvar = "undefined "){
  2. // Do something 
  3. }

From http://www.aspxcs.net/HTML/0009273657.html

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.