Sådan får du mest muligt ud af JavaScript-konsollen

Et af de mest basale fejlfindingsværktøjer i JavaScript er console.log(). Den consoleleveres med flere andre nyttige metoder, der kan føjes til en udviklers fejlsøgningsværktøjssæt.

Du kan bruge til consoleat udføre nogle af følgende opgaver:

  • Output en timer for at hjælpe med simpel benchmarking
  • Output en tabel for at vise en matrix eller et objekt i et letlæseligt format
  • Anvend farve og andre stylingindstillinger på output med CSS

Konsolobjektet

Det consoleobjekt giver dig adgang til browserens konsol. Det giver dig mulighed for at udføre strenge, arrays og objekter, der hjælper med at debugge din kode. Det consoleer en del af windowobjektet og leveres af Browser Object Model (BOM).

Vi kan få adgang til det consolepå en af ​​to måder:

  1. window.console.log('This works')
  2. console.log('So does this')

Den anden mulighed er grundlæggende en henvisning til den førstnævnte, så vi bruger den sidstnævnte til at gemme tastetryk.

En hurtig note om styklisten: den har ikke en fast standard, så hver browser implementerer den på lidt forskellige måder. Jeg testede alle mine eksempler i både Chrome og Firefox, men din output kan se anderledes ud afhængigt af din browser.

Udsendelse af tekst

Det mest almindelige element i consoleobjektet er console.log. I de fleste scenarier bruger du det til at få arbejdet gjort.

Der er fire forskellige måder at udstede en besked til konsollen:

  1. log
  2. info
  3. warn
  4. error

Alle fire fungerer på samme måde. Alt hvad du gør er at videregive et eller flere argumenter til den valgte metode. Det viser derefter et andet ikon for at angive dets logningsniveau. I eksemplerne nedenfor kan du se forskellen mellem en log på infoniveau og en advarsel / fejlniveaulog.

Du har muligvis bemærket fejllogbeskeden - den er mere prangende end de andre. Det viser både en rød baggrund og et stakspor, hvor infoog warn ikke. Selvom warnhar en gul baggrund i Chrome.

Disse visuelle forskelle hjælper, når du hurtigt skal identificere eventuelle fejl eller advarsler i konsollen. Du vil gerne sikre dig, at de fjernes til produktionsklare apps, medmindre de er der for at advare andre udviklere om, at de laver noget galt med din kode.

Stringerstatninger

Denne teknik bruger en pladsholder i en streng, der erstattes af de andre argumenter, du sender til metoden. For eksempel:

Indgang :console.log('string %s', 'substitutions')

Output :string substitutions

Det %ser pladsholderen for det andet argument, 'substitutions'der kommer efter kommaet. Alle strenge, heltal eller arrays konverteres til en streng og erstatter %s. Hvis du passerer et objekt, vises det [object Object].

Hvis du vil videregive et objekt, skal du bruge %oeller i %Ostedet for %s.

console.log('this is an object %o', { obj: { obj2: 'hello' }})

Tal

Strengsubstitution kan bruges med heltal og flydende punktværdier ved hjælp af:

  • %ieller %dfor heltal,
  • %f for flydende point.

Indgang :console.log('int: %d, floating-point: %f', 1, 1.5)

Output :int: 1, floating-point: 1.500000

Flyder kan formateres til kun at vise et ciffer efter decimaltegnet ved hjælp af %.1f. Du kan gøre for %.nfat få vist et antal cifre efter decimalen.

If we formatted the above example to display one digit after the decimal point for the floating-point number, it would look like this:

Input: console.log('int: %d, floating-point: %.1f', 1, 1.5)

Output:int: 1, floating-point: 1.5

Formatting specifiers

  1. %s | replaces an element with a string
  2. %(d|i)| replaces an element with an integer
  3. %f | replaces an element with a float
  4. %(o|O) | element is displayed as an object.
  5. %c | Applies the provided CSS

String Templates

With the advent of ES6, template literals are an alternative to substitutions or concatenation. They use backticks (``) instead of quotation marks, and variables go inside ${}:

const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions

Objects display as [object Object] in template literals, so you’ll need to use substitution with %o or %O to see the details, or log it separately by itself.

Using substitutions or templates creates code that’s easier to read compared to using string concatenation: console.log('hello' + str + '!');.

Pretty color interlude!

Now it is time for something a bit more fun and colorful!

It is time to make our console pop with different colors with string substitutions.

I will be using a mocked Ajax example that give us both a success (in green) and failure (in red) to display. Here’s the output and code:

const success = [ 'background: green', 'color: white', 'display: block', 'text-align: center'].join(';');
const failure = [ 'background: red', 'color: white', 'display: block', 'text-align: center'].join(';');
console.info('%c /dancing/bears was Successful!', success);console.log({data: { name: 'Bob', age: 'unknown'}}); // "mocked" data response
console.error('%c /dancing/bats failed!', failure);console.log('/dancing/bats Does not exist');

You apply CSS rules in the string substitution with the %c placeholder.

console.error('%c /dancing/bats failed!', failure);

Then place your CSS elements as a string argument and you can have CSS-styled logs. You can add more than one %c into the string as well.

console.log('%cred %cblue %cwhite','color:red;','color:blue;', 'color: white;')

This will output the words ‘red’, ‘blue’ and ‘white’ in their respected colors.

There are quite a few CSS properties supported by the console. I would recommend experimenting to see what works and what doesn’t. Again, your results may vary depending on your browser.

Other available methods

Here are a few other available console methods. Note that some items below have not had their APIs standardized, so there may be incompatibilities between the browsers. The examples were created with Firefox 51.0.1.

Assert()

Assert takes two arguments — if the first argument evaluates to a falsy value, then it displays the second argument.

let isTrue = false;
console.assert(isTrue, 'This will display');
isTrue = true;
console.assert(isTrue, 'This will not');

If the assertion is false, it outputs to the console. It’s displayed as an error-level log as mentioned above, giving you both a red error message and a stack trace.

Dir()

The dir method displays an interactive list of the object passed to it.

console.dir(document.body);

Ultimately, dir only saves one or two clicks. If you need to inspect an object from an API response, then displaying it in this structured way can save you some time.

Table()

The table method displays an array or object as a table.

console.table(['Javascript', 'PHP', 'Perl', 'C++']);

The array’s indices or object property names come under the left-hand index column. Then the values are displayed in the right-hand column.

const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table(superhero);

Note for Chrome users: This was brought to my attention by a co-worker but the above examples of the table method don’t seem to work in Chrome. You can work around this issue by placing any items into an array of arrays or an array of objects:

console.table([['Javascript', 'PHP', 'Perl', 'C++']]);
const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table([superhero]); 

Group()

console.group() is made up of at least a minimum of three console calls, and is probably the method that requires the most typing to use. But it’s also one of the most useful (especially for developers using Redux Logger).

A somewhat basic call looks like this:

console.group();console.log('I will output');console.group();console.log('more indents')console.groupEnd();console.log('ohh look a bear');console.groupEnd();

This will output multiple levels and will display differently depending on your browser.

Firefox shows an indented list:

Chrome shows them in the style of an object:

Each call to console.group() will start a new group, or create a new level if it’s called inside a group. Each time you call console.groupEnd() it will end the current group or level and move back up one level.

I find the Chrome output style is easier to read since it looks more like a collapsible object.

You can pass group a header argument that will be displayed over console.group:

console.group('Header');

You can display the group as collapsed from the outset if you call console.groupCollapsed(). Based on my experience, this seems to work only in Chrome.

Time()

The time method, like the group method above, comes in two parts.

A method to start the timer and a method to end it.

Once the timer has finished, it will output the total runtime in milliseconds.

To start the timer, you use console.time('id for timer') and to end the timer you use console.timeEnd('id for timer') . You can have up to 10,000 timers running simultaneously.

The output will look a bit like this timer: 0.57ms

It is very useful when you need to do a quick bit of benchmarking.

Conclusion

There we have it, a bit of a deeper look into the console object and some of the other methods that come with it. These methods are great tools to have available when you need to debug code.

Der er et par metoder, som jeg ikke har talt om, da deres API stadig ændrer sig. Du kan læse mere om dem eller konsollen generelt på MDN Web API-siden og dens levende spec-side.