English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Di solito utilizziamo gli strumenti di debug integrati in Chrome o Firefox per debuggare JavaScript, in questo articolo elenchiamo alcune tecniche di debug per JavaScript. Conoscendole, possiamo risolvere errori e bug in meno tempo, migliorando l'efficienza di sviluppo.
1. debugger
Oltre a console.log, debugger è lo strumento di debug preferito e veloce. Dopo aver eseguito il codice, Chrome si fermerà automaticamente durante l'esecuzione. È anche possibile impacchettarlo in condizioni, in modo che venga eseguito solo quando necessario.
if (thisThing) { debugger; }
2. Visualizzare gli oggetti in tabella
A volte, c'è un gruppo di oggetti complessi da visualizzare. È possibile usarli console.log per visualizzarli e scorrere, o usare console.table per espanderli, rendendo più facile vedere il contenuto che si sta elaborando!
var animals = [ { animal: 'Horse', name: 'Henry', age: 43 }, { animal: 'Dog', name: 'Fred', age: 13 }, { animal: 'Cat', name: 'Frodo', age: 18 } ]; console.table(animals);
3. Utilizzare diverse dimensioni dello schermo
Installare diversi simulatori di dispositivi mobili sul desktop è fantastico, ma nella realtà non è fattibile. Come si può regolare la dimensione della finestra? Chrome offre tutto ciò di cui hai bisogno. Vai nel pannello di controllo e clicca sul pulsante 'Cambia modalità dispositivo'. Osserva le variazioni della finestra!
4. Testare il ciclo con console.time() e console.timeEnd()
È molto utile sapere il tempo di esecuzione di certaini codici, specialmente quando si debugga un ciclo lento. È anche possibile impostare più timer passando diversi parametri al metodo. Vediamo come funziona:
console.time('Timer1'); var items = []; for(var i = 0; i < 100000; i++){ items.push({index: i}); } console.timeEnd('Timer1');
Ecco i risultati generati:
5. Formattare il codice prima di debuggare JavaScript
A volte il codice potrebbe avere problemi nell'ambiente di produzione, ma i tuoi source maps non sono stati distribuiti nell'ambiente di produzione. Non preoccuparti. Chrome può formattare i tuoi file JavaScript. Il codice formattato non è utile come il codice reale, ma almeno si può vedere cosa è successo. Clicca sul pulsante {} del visualizzatore di codice del pannello di controllo di Chrome.
6. Osservare le chiamate di funzione specifiche e i parametri
Nel pannello di controllo di Chrome, è possibile osservare funzioni specifiche. Ogni volta che viene chiamata la funzione, viene stampato l'argomento passato.
var func1 = function(x, y, z) { //.... };
Output:
This is a good way to view the parameters passed to a function. However, it would be better if the console prompts us about the number of formal parameters. In the above example, func1 expects 3 parameters, but only 2 were passed. If this parameter is not handled in the code, it is likely to cause an error.
7. Quick Access to Elements in the Console
There is a faster method than querySelector in the console, which is to use the dollar sign, $('css-selector') to return the first matching item of the CSS selector. $$('css-selector') will return all matching items. If you use an element multiple times, you can save it as a variable.
8. Postman is great (but Firefox is faster)
Many developers use Postman to view AJAX requests. Postman is really great. But opening a new window, writing the request object, and then coming back to test them is quite麻烦.
Sometimes it's easier to use a browser.
When you view using a browser, if you request a password verification page, don't worry about the authentication cookies. Below is how to edit and resend the request in Firefox.
Open the console and switch to the Network tab. Right-click on the required request and select Edit and Resend. Now you can change anything you want to change. Change the title and edit the parameters, then click Resend.
Below are the two requests I initiated with different properties:
9. Breakpoint on Node Change
DOM is an interesting thing. Sometimes it changes, and you don't know why. However, when you are debugging JavaScript, Chrome can pause when the DOM elements change. You can even monitor its properties. In the Chrome console, right-click on the element, and then select Breakpoint in the settings:
The web debugging tools built into Chrome and Firefox are very powerful, and many very practical features are waiting to be discovered by everyone.