كيفية تحقيق أقصى استفادة من وحدة تحكم JavaScript

واحدة من أبسط أدوات تصحيح الأخطاء في JavaScript هي console.log()
. و console
يأتي مع العديد من الطرق الأخرى المفيدة التي يمكن أن تضيف إلى أدوات التصحيح لالمطور.
يمكنك استخدام console
لأداء بعض المهام التالية:
- قم بإخراج مؤقت للمساعدة في قياس الأداء البسيط
- قم بإخراج جدول لعرض مصفوفة أو كائن بتنسيق سهل القراءة
- قم بتطبيق اللون وخيارات الأنماط الأخرى على الإخراج باستخدام CSS
كائن وحدة التحكم
و console
جوه يتيح لك الوصول إلى وحدة التحكم بالمتصفح. يتيح لك إخراج السلاسل والمصفوفات والكائنات التي تساعد في تصحيح التعليمات البرمجية الخاصة بك. يعد console
هذا جزءًا من window
الكائن ، ويتم توفيره بواسطة طراز كائن المستعرض (BOM).
يمكننا الوصول إلى console
بإحدى طريقتين:
window.console.log('This works')
console.log('So does this')
الخيار الثاني هو في الأساس إشارة إلى الأول ، لذلك سنستخدم الخيار الأخير لحفظ ضغطات المفاتيح.
ملاحظة سريعة واحدة حول BOM: ليس لديها معيار محدد ، لذلك ينفذه كل متصفح بطرق مختلفة قليلاً. لقد اختبرت جميع الأمثلة الخاصة بي في كل من Chrome و Firefox ، ولكن قد تظهر مخرجاتك بشكل مختلف اعتمادًا على متصفحك.
إخراج النص

العنصر الأكثر شيوعًا console
للكائن هو console.log
. بالنسبة لمعظم السيناريوهات ، ستستخدمها لإنجاز المهمة.
توجد أربع طرق مختلفة لإخراج رسالة إلى وحدة التحكم:
log
info
warn
error
يعمل الأربعة بنفس الطريقة. كل ما تفعله هو تمرير وسيطة واحدة أو أكثر إلى الطريقة المحددة. ثم يعرض رمزًا مختلفًا للإشارة إلى مستوى التسجيل الخاص به. في الأمثلة أدناه ، يمكنك رؤية الفرق بين سجل مستوى المعلومات وسجل التحذير / مستوى الخطأ.


ربما لاحظت رسالة سجل الخطأ - إنها مبهرجة أكثر من غيرها. ويعرض كلا خلفية حمراء وتتبع مكدس، حيث info
و warn
لا. على الرغم من warn
وجود خلفية صفراء في Chrome.
تساعد هذه الاختلافات المرئية عندما تحتاج إلى تحديد أي أخطاء أو تحذيرات في وحدة التحكم في لمحة سريعة. قد ترغب في التأكد من إزالتها للتطبيقات الجاهزة للإنتاج ، ما لم تكن موجودة لتحذير المطورين الآخرين من أنهم يفعلون شيئًا خاطئًا في التعليمات البرمجية الخاصة بك.
بدائل السلسلة
تستخدم هذه التقنية عنصرًا نائبًا في سلسلة يتم استبدالها بالوسيطة (الوسائط) الأخرى التي تمررها إلى الطريقة. فمثلا:
المدخلات :console.log('string %s', 'substitutions')
الإخراج :string substitutions
و %s
هو نائب عن الحجة الثانية 'substitutions'
التي تأتي بعد الفاصلة. سيتم تحويل أي سلاسل أو أعداد صحيحة أو مصفوفات إلى سلسلة وستحل محل %s
. إذا قمت بتمرير كائن ، فسيتم عرضه [object Object]
.
إذا كنت تريد تمرير كائن ما ، فأنت بحاجة إلى استخدام %o
أو %O
بدلاً من %s
.
console.log('this is an object %o', { obj: { obj2: 'hello' }})

أعداد
يمكن استخدام استبدال السلاسل مع الأعداد الصحيحة وقيم الفاصلة العائمة باستخدام:
%i
أو%d
للأعداد الصحيحة ،%f
للنقاط العائمة.
المدخلات :console.log('int: %d, floating-point: %f', 1, 1.5)
الإخراج :int: 1, floating-point: 1.500000
يمكن تنسيق العوامات لعرض رقم واحد فقط بعد الفاصلة العشرية باستخدام %.1f
. يمكنك القيام %.nf
بعرض عدد n من الأرقام بعد العلامة العشرية.
إذا قمنا بتنسيق المثال أعلاه لعرض رقم واحد بعد الفاصلة العشرية لرقم الفاصلة العائمة ، فسيبدو كما يلي:
المدخلات :console.log('int: %d, floating-point: %.1f', 1, 1.5)
الإخراج :int: 1, floating-point: 1.5
محددات التنسيق
%s
| يستبدل عنصرًا بسلسلة%(d|i)
| يستبدل عنصرًا بعدد صحيح%f
| يستبدل عنصرًا بعوامة%(o|O)
| يتم عرض العنصر ككائن.%c
| يطبق CSS المتوفر
قوالب السلسلة
مع ظهور ES6 ، أصبحت القوالب الحرفية بديلاً عن الاستبدالات أو التسلسل. يستخدمون backticks (``) بدلاً من علامات الاقتباس ، وتنتقل المتغيرات إلى الداخل ${}
:
const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions
كائنات العرض كما [object Object]
في حرفية قالب، لذلك ستحتاج إلى استخدام استبدال مع %o
أو %O
لمعرفة التفاصيل، أو تسجيل بشكل منفصل في حد ذاته.
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.
هناك طريقتان لم أتحدث عنها لأن واجهة برمجة التطبيقات الخاصة بهم لا تزال تتغير. يمكنك قراءة المزيد عنها أو عن وحدة التحكم بشكل عام على صفحة MDN Web API وصفحة المواصفات الحية الخاصة بها.
