Preface: Unconsciously wrote a lot, I hope you can read this article patiently
Any programmer will need to debug the code, whether you are a master or rookie, debugging programs are an essential task. In general, the debugger is written after the code or the test period to modify the bug, often during debugging code more able to reflect the programmer's level and the accuracy of the analysis of the problem. Many beginners in the search for the wrong reasons, always to no avail, spend a lot of time but can not solve some of the final proof is quite simple bug.
In the long-term solution ztree related issues, but also did find a lot of problems actually not what problem, just the programmer will not debug caused, through their daily work observation, there are attitude problems also have the way of thinking problems, so summarize their own experience, for everyone reference (especially rookie), for the master speaking , if you are willing to read this article, but also very welcome to make bricks and provide advice, I believe this can continue to enrich and improve this article, certainly also can help more friends.
Imagine: There was a bug, someone took a few minutes to get it done, someone spent half a day or a day can not find the reason. Are you willing to be the current person or the latter? If you want to be the former, please read this article carefully.
This article is mainly to help you in debugging code, how to establish a solution to the problem of the idea. Therefore, the specific debugging methods of different browsers are not specifically introduced. (in the online about Chrome, Firefox, IE and other browser specific debugging methods have been many, here is not described.) In addition, as the saying goes-"JS, HTML and CSS is a", so in the narration will also be slightly with HTML and CSS content.
What should I do if I encounter an error?
Hard to write a large piece of code but can not run, how to do? ...... The first two days also normal code how today error, how to do? ...... The same code in this page normal how to the other page on the problem, how to do? ...... Have you ever met any of these situations? Did you get burned and upset with your mistakes? ("No matter how far the road, how many difficulties and hardships, it is impossible to stop my progress!") "--Tang Master)
1, adjust the mentality
The problem is normal, but it is not normal. So we need to be cool when it comes to finding problems. Do not care who is standing behind, do not care about the distance on the line time and a few hours, let yourself calm down, deep breath-come, not just a small problem. All bugs are under my control!
Taboo: If there is a problem, ask for help, this will lead to frequent interruptions, but also not conducive to their skills to improve. Ask for help only after you have worked hard enough to find a solution. Also, when you ask a question, try to describe the problem as clearly as possible.
2. Look for Features
The premise of solving the error is to find the error and find the premise of the error ... Of course, to "Look for"! For a simple error message can fully take advantage of the debugging tool tip: XXXX line what error occurred. If this information is 100% valid, then you do not need to read this article.
The wrong appearances we meet are generally divided into the following types of
- Direct report JS syntax error
This is generally the most easy to solve, do not need me to the nonsense ...
- JS error, but the error location is not the root cause of the problem
Most of this can be solved, but sometimes it's quite a headache when you don't know exactly where to cite it.
- JS no error, but invalid function
This situation is worse, completely without a clue ... Then I'll tell you that it's often easier to finally fix the wrong way.
Depending on the feature, it is often possible to quickly locate the wrong approximate location for further problem-finding purposes.
3, suspicion of all
When someone tells you something is wrong with the code, our first response is often: "Impossible!" "Are you looking wrong?" "I have just run it well," said the man. "If you have the above idea, then you need to pay attention!" These ideas are dangerous, if you want to solve the problem, then we will have to suspect any possible things, to feature-based, do not subjectively determine which places will certainly not be wrong.
Second, how to let the wrong to show the prototype?
The main purpose is to allow us to have a good attitude to deal with the problem, the mood to keep calm can make our thinking more agile, grasp the characteristics can let us find clues faster, doubt everything can let us have more ideas to find errors. ("Do not turn the doer to show the original, do not want to turn over the mountain!") "--monkey Brother)
1, the simplification of the complex
Clinical manifestations: Inexplicable error, inconvenient debugging, simply see the code can not explain the cause of the error.
Main causes: JS scripting conflict, CSS Conflict, Dom ID conflict, DOM tag missing, etc. due to conflict caused by the source of the bug
Troubleshooting: Skilled use of the Delete/backspace key, the code is continuously removed from the region until the symptoms disappear, the last area of the deletion is likely to be the cause of the error. Further finding the source you can use this method repeatedly in a region definition that uses smaller units in the target area.
Attention:
- For JS code recommendations to the class library, respectively? Function? Behavior Unit to delete test
- For the HTML code suggested by the page structure to delete the most internal tag, by the inside and outside, so that you can quickly find the error caused by the missing tag, but also to ensure that every time the deletion is the entire code, to avoid the deletion caused by new errors.
- Recommended for CSS code follow CSS file? Define the class series? The behavior unit deletes the test in bulk
Bogey: Do not delete the part that is related to the relevant function.
Side effects: Using this method can also be very good to confirm that the cause of the error is JS or CSS caused.
2. The Clues
Clinical Manifestation: The error information is accurate, can follow the error of the prompt, and use "simplification" can basically locate the error type
Main causes: Basic grammatical error, logical error, not rigorous (most common: array subscript out of bounds, NULL NULL pointer caused by object not found, undefined uninitialized, Nan numeric calculation error, etc.)
Troubleshooting: Using the browser's debugging tool (F12 is a good function key): Tracking code, using the Console.log output monitoring object (ie invalid), using alert monitoring (the most helpless method for extreme situations); Load debug code in front of the command line, there will be a miraculous effect!
Attention:
- For the case without JS error, directly debug the invalid function code. Sometimes I find that the reason why the function is invalid is that the code is not called! (Isn't it ridiculous?) I confess that I have made such a mistake. )
- Logic error is often not easy to think clearly, this time can be properly combined with the "simplification" of the idea of debugging.
- When you are using a JS library similar to JQuery, if the error message is in the JS Library, first to replace the uncompressed JS code for debugging, and then analyze which code of your own will invoke the relevant features.
Bogey: the Dead! When this method still fails to find the source of the error, it means that this is not an accurate error message and there must be other potential factors in generating the error. Change the entry point immediately and don't waste time in one place for a long time. (At this point, you can refer to the next method: "Repeat control")
3. Repeated control
Clinical manifestations: The use of common methods is difficult to locate errors, the first two methods how to use are still unable to find the clue.
Main causes: complex logic, the function of binding to each other difficult to peel, Page object content complex, some pages are normal page is not normal, compatibility issues, etc.
Troubleshooting: To deal with this complex problem, the troubleshooting method will be cumbersome, but not a particularly advanced technology, just need to do more physical work.
- method One : Check the suspect code, refine the function point, modify only one place at a time, modify the test once, until you find the key code that caused the error.
- method Two : Make the simplest demo only to achieve the required functions, when the function is normal, and the error of the formal code to compare (the comparison can be appropriate to use method one)
- method Three : the normal function (or error) of the code as a prototype, modify a place to generate a test backup, each test case only one place with the original code, numbering, in a special environment to test each, Check the root cause of the error (I used this method to solve the Korean system under the IE8 loading company internal Flash can not be normal voice of the bug)
Attention:
- You must be patient with this method.
- This method of low technical content, anyone can quickly grasp, solve some of the incurable diseases basically can be said to be charm!
Bogey: impatience, carelessness
4. Accumulate experience
Clinical manifestations: Some browser error, incident response anomaly, JS Operation Dom Invalid, PC and touch screen system function inconsistent, etc.
Main causes: Various compatibility issues
Troubleshooting: For some of the obvious characteristics of the error to memorize in the chest, see these situations can immediately think of what should be the cause. (The most obvious example: JSON object more than a comma case, only ie error)
Attention:
- There is a very basic problem, but there are a lot of beginners error-do not understand the page HTML, CSS, JS loading order, resulting in JS operation failed. (Go to Google or Baidu search: "html CSS JS loading order")
- The daily work must be careful, observe diligently. Take the job of finding mistakes seriously, and you can write down some very special cases.
- Skilled use of Google, Baidu and other search engines, and sometimes their first encounter, others have known how to solve the situation.
Bogey: carelessness, superficial understanding
5. Details determine success or failure
The above four methods of finding errors all depend on one core-the details! Details tend to be more important than your skill level. If you say a word of exaggeration, how many advanced techniques will you be able to do? Take your work seriously and finish it! But remember, when you pay attention to the details, you should not be far from the opportunity to do advanced technology.
Third, how to correct the error?
Old procedures should have been deep experience, change the most headache or wrong, once found the error, the real solution may really only a few minutes. Here is a summary of some common error causes and modifications:
1, basic grammar, language Foundation
are commas, semicolons, double quotes, single quotes, and various brackets estimated to have caused your code errors? These things are important to know when to use, and do not streamline the symbols to simplify the code.
For example, {} After a statement such as If/for, it is best to bring it.
Add, for the number of JS in the range of numbers I hope you have a certain understanding, because this range is certainly not the same as in the background language long. (More than one friend has told me that Ztree will automatically modify the ID of the node, when I see the case, it was a digital overflow!) )
2. Strict conditions
For arrays or manipulating object properties, make the conditional judgment statement write as complete and comprehensive as possible.
For example: When judging the A.ABC, it is best not to forget to determine the existence of a, or the operation of the array to determine whether the array exists, whether the subscript to operate out of bounds and so on.
3. Note Compatibility (CSS & JS)
Be wary of inconsistencies or errors in some browsers, many of which are compatible. If your experience is not enough, go directly to Google or Baidu. Some of the compatibility issues that you often get in touch with slowly will be kept in mind.
Add, sometimes pay attention to the definition of the page head, once a friend asked me ztree abnormal problems, the final discovery is only half of the story.
4. Logical Traps
Conditions are too complex, and loops and judgments are often the factors that lead to logical traps. Encounter this situation, if you really can not solve so please a side of the master to, let him help you explain. I believe that, except for those who are a bit autistic, others will be willing to help you solve the problem (if you don't hate yourself too much, hehe)
Add: Read more about refactoring technical books! It's going to make you a lot better.
5. Asynchronous loading
In fact, the problem of asynchronous loading is often a logical trap, but I have to come up with a special narrative, because there are too many people who make mistakes!!!! Here is a detailed approach to the process:
- For an exception to asynchronous loading, follow these steps to troubleshoot:
1) does the page have an error, do you want to execute the code to the AJAX section? (see next if normal)
2) using the browser's debugging tools to monitor the network, Ajax loaded URL address is correct? (see next if normal)
3) using the browser's debugging tools to monitor the network, the parameters passed to the URL is correct? (see next if normal)
4) using the browser's debugging tools to monitor the network, the data returned from the URL is correct? (see next if normal)
5) write debug code in success of Ajax and debug the correct processing method after asynchronous loading
If the above steps are normal, then I can tell you that asynchronous loading itself is all normal, but also the wrong thing to do? Keep looking down.
- When asynchronous loading is OK, you need to consider another important question, which is the easy mistakes that I made in the previous article, "The mental retardation of the years we Love" (rookie must see), the negligence of asynchronous loading
1) do not execute Ajax immediately after executing the code that should be run after the asynchronous loading is complete. Because when you execute this code, AJAX is not done at all. (most obvious: the runtime is good and bad, but if I join the alert I'll find it's normal every time)
In this case, please transfer your code to AJAX success or error to execute
2) when you set some special switch, do not forget the AJAX error inside the reset, or it is likely because of a network anomaly, will cause your page JS function failure. Such errors are often mine-level and difficult to detect.
6, the Magical settimeout
For mobile devices or some special cases, you can use SetTimeout to solve the problem appropriately.
I encountered a case of exception: There are two JS events because different functions in the same DOM operation will cause IE8 crash, obviously this is IE bug, but I can not ask Microsoft to do what ... End up using SetTimeout to allow one of the features to be delayed by 100-200 milliseconds and then done easily!
7. Don't hang in a tree
The front-end people are very depressed to adapt to the N-more browser, often encounter some of their own problems can not be solved (because it is a browser bug), what to do with this situation? Generally find out if there is no hacker method, if not, then a different way of thinking, to see if there are other options to achieve similar functions. If all sorts of efforts have been made ... Others are not satisfied, then tell him the browser bug, let the project manager to decide how to deal with it-this situation died without regret!
Written here, basically can be said to be all out of the, hoping to have a little attention to you, hoping to make you feel a touch, feel some déjà vu. The main I still hope you can quickly improve their skills, get a lot of wages, let yourself become a technical cow!
Finally, I would like to thank a few good friends who helped me with my manuscript review.
JS Code Debugging Experience Summary (rookie must read)