Favorites: Javascript script debugging experience

Source: Internet
Author: User
With the development of JavaScript programming, you will begin to understand the opaque error messages provided by JavaScript. Once you understand your common mistakes, you will soon know how to avoid them so that you can write Code Fewer and fewer errors. Programming is actually a technology that can make rapid progress over time. However, no matter how skilled you are, you still need to spend some time debugging your code. If you have a homework or jacascript programming experience, you will know that a considerable amount of time is spent on debugging. This is normal-this is only one of the things that programmers must do. In fact, according to a lot of research, Program The average staff time is 50% of the time spent solving code errors.

The key is to learn how to effectively debug your program. I have some tips to help you solve why the program is not running as expected, or to help you avoid writing a lot of wrong code first:

1. Print variables in different ways
2. Pay attention to General errors
3. Think about encoding first
--------------------------------------------------------------------------------
If JavaScript fails to capture your error, you cannot view the code to find the error. Sometimes printing the variable will help you. The simplest way is to use an alert () as follows ():

  1. // Thegreeting gets a name using getname, then presents
  2. // One or two alert boxes depending on what the name is
  3. // Function getname ()
  4. {
  5. VaRFirst_name = prompt ("What's your first name? ","");
  6. VaRLast_name = prompt ("What's your last name? ","");
  7. VaRThe_name = first_name +""+ Last_name;
  8. Alert ("In getname, the_name is :"+ The_name );
  9. }

-----------------------------Error found--------------------------------------------------
1. General program error
Most errors are just boring syntax errors. Remember to close the quotation marks. Braces and parentheses take a long time, but fortunately JavaScript's automatic error detector can catch most of these errors. Although JavaScript error detectors are constantly improved with the increasingly complex browser, some errors still slide away. The following are some common errors to be aware:

2. obfuscated variable or function name
Errors produced by uppercase and plural variables and function names are often annoying, and sometimes JavaScript error detectors cannot capture them. By establishing and sticking to a naming convention for variables and functions, these troubles will be greatly reduced. For example, I define variables with lowercase letters, replace spaces (my_variable, the_data, an_example_variable) with underscores, and use built-in symbols to represent functions (addthreenumbers (), writeerror (), and so on ). I avoid using any plural, because I always forget whether or not those variables are plural.

3. Reserved Words are accidentally used
Some words cannot be used as variable names because they are already used by JavaScript. For example, a variable named "if" cannot be defined, because it is actually part of JavaScript-you may encounter various troubles if you use "if. When you get crazy with variables named "if", a variable named "document" is very attractive. Unfortunately, "document" is a JavaScript Object. Another common problem is to name the variable "name" (The form element has the "names" attribute ). Naming a variable as "name" won't always lead to problems, but sometimes-this will be even more confusing-this is the reason to avoid using the "name" variable.
Unfortunately, different browser browsers have different reserved words, so there is no way to know which words should be avoided. The safest way is to avoid using words and HTML words that have become part of JavaScript. If you encounter problems with variables and cannot find any errors, try to change the variable name. If it succeeds, you may have avoided reserved words.

4. Remember to use two equal signs for logical judgment.
Some Web browsers can capture such errors, but some cannot. This is a very common error, but if the browser cannot be pointed out for you, it will be hard to find out. The following is an example of this error:

    1. var the_name = prompt ( " What's your name? " , " " );
    2. If (the_name = "the Monkey" )
    3. {
    4. alert ( "Hello monkey! " );
    5. } else {
    6. alert ( "Hello Stranger. " );
    7. }

This code will generate "Hello monkey !" Warning dialog box-no matter what you typed in the prompt-this is not what we want. The reason is that there is only one equal sign in the if-then statement, which tells JavaScript that you want to make one thing equal to the other. Suppose you typed "Robbie the robot" in the prompt ". At first, the value of the_name is "Robbie the robot", but then the if statement tells JavaScript that you want to set the_name to "the monkey .". Therefore, JavaScript is very happy to execute your command and send a "true" message to the if-then statement. "Hello monkey!" is displayed every time in the result warning dialog box !". This sinister mistake will drive you crazy, so pay attention to using two equal signs.

5. variables are accidentally enclosed in quotation marks, or strings are left in quotation marks.
I encounter this problem from time to time. The only way for JavaScript to distinguish between variables and strings is that strings have quotation marks and variables do not. The following is an obvious error:

    1. VaRThe_name ='Koko the gorilla';
    2. Alert ("The_name is very happy");

Although the_name is a variable, the program will generate a warning dialog box prompting "the_name is very happy. This is because once JavaScript sees that the quotation marks enclose something, it will not be considered, so when you put the_name in the quotation marks, you will prevent javascript from looking for it from the memory. The following is an extension of this type of error that is not obvious:

    1. Function wakemein3 ()
    2. {
    3. VaR the_message ="Wake up! Hey! Hey! Wake up !!!! ";
    4. SetTimeout ("Alert (the_message );",3000);
    5. }

The problem here is that you tell JavaScript to execute alert (the_message) three seconds later ). However, the_message will no longer exist in three seconds because you have exited the function. This problem can be solved as follows:

    1. FunctionWakemein3 ()
    2. {
    3. VaRThe_message ="Wake up! ";
    4. SetTimeout ("Alert ('"+ The_message +"');", 3000 );
    5. }

Put the_message out of quotation marks and run the "alert ('wakeup! '); "You can get what you want after the reservation is made by setTimeout. This is just some errors that may be difficult to debug in your code. Once they are found, there are different or good or bad methods to correct the error. You are lucky because you can benefit from my experience and mistakes.

-------------------------------Clear Error------------------------------------
Sometimes it is difficult to find an error, but it is only the first step. Then you mustClear Error. The following are some things that should be done when clearing errors:

First copy your program

Some errors are hard to be cleared. In fact, sometimes, when you eradicate errors, you will destroy the entire program-a small error will drive you crazy. Saving your program before debugging is the best way to ensure that errors do not take advantage of you.

One error fixed at a time
If you know there are several errors, you should correct one and test the result before starting the next one. One correction of many errors without testing your work will only lead to more errors.

Be alert for obfuscation errors
Sometimes you know there is an error, but you don't really know why. Suppose there is a variable "Index". For some reason, "Index" is always 1 smaller than you expected. You can do one of the following two things: sit there for a while, solve why it gets smaller, or just shrugged; Add 1 before using "Index", and then proceed. The latter method is called obfuscation programming. When you start to think, "What's going on?-Why is index 2 instead of 3? Okay... I want to make it work now and modify the error later ." You are attaching a protective plaster to a potential injury.
Confused programming may be useful in the short term, but you can see the long term bad luck-if you don't fully understand your code to the extent that you can actually clear the error, that error will come back to bother you. It can either return in another way that you cannot solve the weird error, or when the next poor cursed soul reads your code, he will find your code very difficult to understand.

Search for minor errors
Sometimes, for programmers, the ability to cut and paste code is a bad thing. Generally, you write some JavaScript code in a function, and then cut and paste them into another function. If there is a problem with the first function, there are problems with both functions. I am not saying that you should not cut or paste the code. But errors will multiply in some way. If you find a mistake, you should look for other similar errors. (Or know exactly what will happen before several versions are created .) Misspelling of variable names occurs multiple times in a javascript code. If the_name is misspelled into teh_name in one place, you will find this error elsewhere.

If all other methods fail
If you are sitting there staring at an error and cannot point out what is going on (or no error is found, but because the program cannot run correctly, you know there is an error ), you 'd better leave the computer. Read a book, take a walk in the corner, or get a delicious drink-Do something, do anything, but don't think about programs or problems. In some cases, this technology is called "brewing" and the effect is very good. After you take a break and relax, try again to find out the error. You will get a clear picture. Brewing works because it frees you from confusion. If you go too far along a wrong path, you may find that you cannot turn around. In this case, we 'd better open up a new path. I know it will make people angry, but it does work. Really!

If the above method is not successful...
Ask for help from others. Sometimes, your thoughts form a definite pattern. You can only gain insight into the problem from a different perspective. In a structured programming environment, programmers regularly review others' code. This can be called "Code Review", which not only helps to eliminate errors, but also provides better code. Don't be afraid to show your JavaScript code to others. It will make you a better JavaScript programmer.

But the absolute best way to eliminate errors is...

Code without errors is created at the beginning.

-------------------------------No error code is created---------------------------------------
The key to programming is that the program is written to people, not to computers. If you can understand that others may read your JavaScript, you will write clearer code. The clearer the code, the more difficult it is to make mistakes. Clever code is cute, but this clever code will produce errors. The best rule of thumb is kiss, that is, keep it simple and Sweetie (keep simple and cute ). Another helpful technique is to make comments before writing code. This forces you to think about it first. Once a comment is written, you can write the code below it.
The following is an example of writing a function using this method:

Step 1: write comments

Step 2: Fill in the code
This method not only forces you to think before writing code, but also makes the coding process look easier-by dividing tasks into small, easy-to-code parts, your problem does not look like Mount Everest, but like a group of pleasant ups and downs.

Last... End each statement with a semicolon.
Although it is not strictly required, you should develop the habit of ending each statement with a semicolon, which can avoid further code in this line. If you forget the extra points, the next line of good code will suddenly generate an error. Initialize the variable as "Var" unless you have a better reason not to do so. Using "Var" to localize variables can reduce the chance of confusion between one function and another unrelated function.
Now that you know how to code, let's learn how to make

Your JavaScript code runs quickly.>
---------------------------------------------------------
Speed-based JavaScript code optimization
1. Restrict the workload in the cycle
2. Customize the if-then-else statement in the most likely to impossible order
3. Expression for minimizing repeated executions

From: http://blog.csdn.net/java2000_net/archive/2008/10/10/3046871.aspx

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.