With JavaScript programming in depth, you will begin to understand the opaque error messages given by JavaScript. Once you understand the general mistakes you make, you will soon know how to avoid them, so you will have fewer errors in the code you write. Programming is actually a technology that can progress rapidly over time. But no matter how skilled you become, you still have to spend some time debugging your code. If you have done homework, or have had jacascript programming experience, you will know that quite a lot of time is spent on debugging. It's normal-it's just one of the things programmers have to do. In fact, according to a lot of research, programmers spend an average of 50% of their time fixing errors in the code.
The key is to learn how to effectively debug your program. I have some tips to help you troubleshoot why the program doesn't work as it should, or to help you avoid writing a lot of wrong code first:
1. Print out variables in different ways
2. Note General errors
3. Before you encode, think well
--------------------------------------------------------------------------------
If JavaScript does not capture your errors, you do not find errors by looking at the code, and sometimes printing out variables will help you. The simplest approach is to use an alert () as follows:
- Thegreeting gets a name using GetName, then presents
- One or both alert boxes depending on what's the name is
- function GetName ()
- {
- var first_name = prompt ("What ' s your first name?", "");
- var last_name = prompt ("What's your last name?", """);
- var the_name = first_name + "" + last_name;
- Alert ("in GetName, The_name is:" + the_name);
- }
----------------------------- found an error --------------------------------------------------
1. General Procedural errors
Most errors are just boring grammatical errors. Remembering to close those quotes, curly braces and braces can take a long time, but fortunately the JavaScript automatic error detector captures most of these errors. While JavaScript error detectors are constantly being perfected with increasingly complex streams, some errors still slip away. Here are some common mistakes to keep in mind:
2. Confusing variable names or function names
Errors caused by uppercase and plural variables and function names are annoying and often occur, and sometimes JavaScript error detectors cannot capture them. By creating and persisting a naming convention on variables and functions, the number of these hassles is greatly reduced. For example, I define variables in all lowercase letters and use underscores instead of spaces (My_variable,the_data, an_example_variable), with built-in symbols to represent functions (Addthreenumbers (), Writeerror (), and so on). I avoid using any plural, because I always forget that those variables are not plural.
3. Accidental use of reserved words
Some words cannot be used as variable names because they are already in use by JavaScript. For example, you cannot define a variable called "if" because it is actually part of the JavaScript-if you use "if", you will encounter various problems. A variable called "document" is tempting when you get mad by using a variable named "if". Unfortunately, "document" is a JavaScript object. Another frequently encountered problem is to name the variable "name" (the form element has the "names" attribute). Naming the variable "name" doesn't always go wrong, just sometimes-it's more confusing-that's why you avoid using the "name" variable.
Unfortunately, different browser types have different reserved words, so there's no way to know which words to avoid. The safest way is to avoid using words that have already become part of JavaScript and the words used by HTML. If you're having problems with a variable and can't find out what's wrong, try changing the variable name. If it succeeds, you may be avoiding the word of retention.
4. Remember that you should use two equals sign in logical judgment some of the browser can catch this error, but some can't. This is a very common mistake, but it's hard to find out if the browser doesn't point out for you. Here is an example of this error:
- var the_name = prompt ("What ' s your name?", " ");
- if (The_name = "The monkey")
- {
- Alert ("Hello monkey!");
- } Else {
- Alert ("Hello Stranger.");
- }
This code will produce "Hello monkey!" Warning dialog box-no matter what you're knocking at the tip-it's 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 something equal to another. Suppose you hit "Robbie the Robot" in the tip. At first, the value of the variable the_name is "Robbie the robot", but then the IF statement tells JavaScript that you want to set the The_name to "the Monkey." So JavaScript is happy to execute your command, send a "true" message to the If-then statement, and the Result warning dialog box appears "Hello monkey!" every time. This insidious mistake can make you mad, so pay attention to using the two equals sign.
5. Accidentally add quotation marks to the variable, or forget to enclose the string in quotation marks . I have encountered this problem at times. The only way for JavaScript to differentiate between variables and strings is if the strings are quoted and the variables are not. The following is an obvious error:
- var the_name = ' Koko the gorilla ';
- Alert ("The_name is very happy");
Although The_name is a variable, the program also produces a warning dialog box that prompts "The_name is very happy." This is because once JavaScript sees quotes around something it no longer considers it, so when you put The_name in quotes, you stop JavaScript from looking for it from memory. The following is a less obvious extension of this type of error:
- function WakeMeIn3 ()
- {
- var the_message = "Wake up! hey! hey! WAKE up!!!! ";
- SetTimeout ("alert (the_message);", + );
- }
The problem here is that you tell JavaScript to execute alert (the_message) after three seconds. However, after three seconds, the the_message will no longer exist because you have exited the function. This problem can be solved as follows:
- function WakeMeIn3 ()
- {
- var the_message = "Wake up!";
- SetTimeout ("alert ('" + the_message+ "');";
- }
Put the the_message outside the quotation marks and command "alert (' wakeup! ');" By settimeout, you can get what you want. This is just some of the hard-to-debug errors that might be in your code. Once they are found, there are different or good or bad ways to correct the error. You are lucky because you can benefit from my experience and mistakes.
------------------------------- Clear the error ------------------------------------
Finding errors, sometimes difficult though, is only the first step. Then you must clear the error . Here are some things you should do when you clear the error:
First, copy your program.
Some errors are difficult to remove. In fact, sometimes when you eradicate a mistake, you break the whole program-a small mistake that makes you crazy. Saving your program before you start debugging is the best way to make sure that the error does not take advantage of you.
Fix one error at a time
If you know that there are several errors, you should fix one, test its results, and start next. Correcting many errors at once without checking your work will only incur more errors.
Beware of confusing errors
Sometimes you know there's a mistake, but don't really know why. Suppose there is a variable "index", for some reason "index" is always 1 smaller than you expect. You can do one of the following two things: sit there for a while, solve why it's getting smaller, or just shrug your shoulders; add 1 before using "index" and continue. The latter method is called obfuscation programming. When you start thinking "What's the matter-why is index 2 instead of 3?" All right... I'll let it work right now, and then I'll revise the error later. "You're putting a piece of protective plaster on a potential mishap. Confusing programming can be useful in the short term, but you can see the long-term doom-if you don't fully understand your code to the extent that you can really erase the error, that error will come back to haunt you. It either comes back in another weird way that you can't solve, or when the next poor cursed soul reads your code, he will find your code very difficult to understand.
Looking for small errors
Sometimes, the ability to cut and paste code is a bad thing for programmers. In general, you will 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, then two functions are now problematic. I'm not saying you shouldn't cut and paste the code. But mistakes can breed in some way, and if you find a mistake, you should look for other errors similar to the one. (or know exactly what happens before you make several versions of it.) The spelling error of the variable name will appear in a JavaScript code all of a sudden-in a place where the_name is misspelled into Teh_name, you have the opportunity to find it elsewhere.
If all the other methods fail,
If you're sitting there staring at a mistake and can't figure out what's going on (or you don't see the error at all, but because the program doesn't work correctly and you know there's an error), you'd better walk away from the computer. Read a book, take a Walk in the corner, or grab a nice drink-do something, anything, but don't think about the program or the problem. This technique is called "brewing" in some cases, and the effect is very good. After you have a little rest and relaxation, try to find out what's wrong. You'll get a clearer picture. "Brewing" works because it frees you from the clutter of your mind. If you go too far along a wrong road, you sometimes find that you can't turn around. It is better to open a new road in this case. I know it's going to get really angry, but it works. It's true!
If the above method is not successful ...
Ask someone for help. Sometimes your mind will form a stereotype, and you can only look at the problem in a different light. In a structured programming environment, programmers periodically review people's code with each other. This can be appropriately called "Code review", not only to help eliminate errors, but also to get 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 ...
Create code without errors at the outset.
------------------------------- Create code with no errors ---------------------------------------
The key to compiling a program is that it is written to people, not to computers. If you can understand that other people might read your JavaScript, you'll write a clearer code. The clearer the code, the less likely you are to make mistakes. Smart code is cute, but this clever code can produce errors. The best rule of thumb is KISS, which is keep It simple,sweetie (keep it simple and cute). Another helpful technique is to annotate the code before writing it. This forces you to think well before you start. Once you've written the comment, you can write the code underneath it.
Here is an example of a function written in this way:
First step: Write a comment
Step two: Populate the Code
This first-note strategy not only forces you to think before you write code, but makes the coding process easier to read-by dividing the task into small, easy-to-encode parts, your problem doesn't look much like Mt. Everest, like a group of delightful rolling hills.
finally ... always end Each statement with a semicolon.
While not strictly necessary, you should develop the habit of ending each statement with a semicolon, so that you can avoid the code behind this line. Forget to add a semicolon, the next line of good code will suddenly produce an error. Initialize the variable to "var" unless you have a better reason not to. Using "Var" to make a variable local can reduce the chance that a function will be confused with another unrelated function.
Well, since you already know how to encode, let's learn how to make
your JavaScript is running fast . >>
---------------------------------------------------------
Optimize JavaScript code by speed
1. Limit the amount of work in the Loop 2. Customize the If-then-else statement, in the most probable to the most improbable order 3. Minimizing repeated execution of an expression
Favorites: Debugging experience with Javascript scripts