In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what is the use of the console?" in the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Break through the comfort zone
Also as a developer, it is undeniable that the group of programmers will always optimize the workflow to make it more efficient. However, this can easily lead us into a misunderstanding, making it difficult for us to break through the usual workflow, and then close our ears and listen to think that there is no better working method and process than now.
The general workflow of Web developers is to write the code in IDE, save it, and then refresh the test in the browser. At the same time, you can use the browser's DevTools to adjust the CSS, and you can also test the performance of the product on different resolutions and mobile devices. You can debug our script by adding a console.log () statement where you need to delve deeper.
If console.log () is abused in the final product, if you keep turning on DevTools while you are surfing the web, you will see a lot of debugging information in the console that should not have appeared in the final product.
Let me introduce you to commands other than console.log () and see if they will bring any new inspiration to your work.
Multiple uses of the console
We may be used to using console.log ("parameters") to understand what is going on in the program, which is generally sufficient for the type of output of characters or numbers, but it is not so easy when outputting data such as objects or arrays.
The first trick is to put curly braces on variables so that you can print not only their values, but also their names, which makes it easier for us to locate where the values come from in the log.
one
two
three
Let x = 2
Console.log (x) / / 2
Console.log ({x}) / / {x: 2}
Format log
You can format strings in console.log by using percent operators to refer to record values in different formats. Here is the definition of the operator type:
% s: string
% I or% d: integer.
% f: floating point number.
C:CSS style.
% o: extensible DOM element.
% O: extensible JavaScript object.
You can try them on the console, starting with examples of strings and integers:
one
two
Console.log ('% ix% s developer', 10, 'console')
/ / 10x console developer
If you plan to format numbers as integers, you can use the following example:
one
two
Console.log ('% i', 12.34455241234324234)
/ / 12
The c operator allows you to customize the style of the output log using the CSS style
one
Console.log ('% cPay attention to me', 'color:firebrick;font-size:40px')
For more logging features, you can check the official documentation to see what has been implemented to avoid duplicating the wheel.
Grouping log
You can use console.group () to group logs to display them as extensible and collapsible groups.
one
two
three
four
five
six
seven
Const label = 'The Millenium Falcon Crew'
Console.group (label)
Console.log ('Leia')
Console.log ('Han')
Console.log ('Chewie')
Console.log ('Ben')
Console.groupEnd (label)
You can nest groups and use console.groupCollapsed () not to expand them by default:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
Const extendedlabel = 'The Millenium Falcon Crew extended'
Const meat = 'Humanoids'
Const metal = 'Droids'
Console.group (extendedlabel)
Console.groupCollapsed (meat)
Console.log ('Leia')
Console.log ('Han')
Console.log ('Chewie')
Console.log ('Ben')
Console.groupEnd (meat)
Console.group (metal)
Console.log ('R2D2')
Console.log ('C3PO')
Console.groupEnd (metal)
Console.groupEnd (extendedlabel)
Log console filtering
In addition to console.log, you can also use console.info (), console.error (), and console.warning () instead. With these statements, you can filter the messages you see in the console in the console sidebar or drop-down list. This makes it easier to find your own log messages in third-party scripts and other scripts in the project.
Other console commands
You may have created variables during debug to count the number of times a method has been called or executed. Another method, console.count () and console.countReset (), is recommended here, through which you can create any number of variables and distinguish them by tags.
one
two
three
four
five
six
seven
Console.count ('Chocula'); / / Chocula: 1
Console.count (); / / default: 1
Console.count ('Chocula'); / / Chocula: 2
Console.countReset ('Chocula')
Console.count (); / / default: 2
Console.count (); / / default: 3
Console.count ('Chocula'); / / Chocula: 1
You can also use the console.time () method to count the total time spent on code execution:
one
two
three
four
five
Console. Time ('go')
For (let I = 0; I
< 200000; i+=1) { let x = Math.random()*2000; } console.timeEnd( 'go' ); // go: 11.7861328125 ms 使用 console.dir()不仅可以显示内容,还可以显示你发送的数据类型。例如,如果你想要一个节点的XML表示,你可以使用console.dirxml()。而console.table()对于显示JSON数据作为一个可排序的表格显示效果也很好。 使用实时表达式Live Expression替代console.log 使用 console.log() 来监测那些变化范围很大的数值时,不仅低效且困难。你可在在开发人员工具中通过点击"眼睛"图标来激活Live Expression功能。它可以将你想要关注的数值pin在工具顶端。 例如,你可以先输入document.activeElement 来试试。该表达式表示当前获得焦点的元素。 在这有一点需要说明,因为Live Expression并不和某一个站点及域名所关联,所以它会一直保留在你的DevTools中。因此建议在完成一项调试后及时删除它们,以免为调试其他站点时带来不必要的麻烦。 使用控制台处理当前文档 开发人员工具中的控制台不仅仅是用于显示日志的一种方式。它是一个REPL,可让您编写和执行JavaScript并使用自动完成功能了解当前文档的可用方法和属性。 你可以试试,在开发人员工具的控制台,输入doc并按下tab,它会自动将其转为document。如果输入'.' 你会看到所有document可用的方法和属性。这是一种学习可用方法和属性的有趣且简单的方法之一,这样可以使你在短时间内写出大量代码。In addition, there are many shortcuts for you to use the console utility to interact with the current document. Some of them are:
$_ stores the result of the last console command. So if you typed 2percent 2 and pressed enter, you are typing $_ which will provide you with 4 directly.
$0 to $4 is the stack of elements you select through the Elements tab, and $0 is the currently selected element.
$() Select the elements in the page through the selector
$() returns an array of elements that match the given selector. This command is equivalent to document.querySelectorAll ().
$x () allows you to select DOM elements through XPATH.
Copy () copies everything you provide to the clipboard.
Clear () clears the console.
GetEventListeners (node) returns the event listener registered on the specified object.
MonitorEvents (node, events) monitors and records events that occur on an object.
Monitor (method) creates a log whenever a method is called.
Some of these methods are powerful, but we may have implemented a series of console.log () statements ourselves without knowing it.
For example, the following usage scenarios:
one
two
MonitorEvents (window, ['resize',' scroll'])
MonitorEvents ($0, 'key')
A log is recorded each time the window is scrolled or resized. The second example is interesting because it records any keystroke behavior on the currently selected element.
The following code lists all the a tags on the page (because $$('a') is short for document.querySelectorAll ('a')) and displays it in a sortable table. The array, as the second parameter of the table method, defines the columns of the table. Otherwise, each attribute of the link will become a column, which will be difficult to browse. Not only is this table sortable, but you can also copy and paste it-for example, into Excel.
one
Console.table ($$('a'), ['href',' text'])
Instead of using complex JavaScript to filter these results, you might as well try the CSS selector. For example, if you want to get a table of src and alt information about all the non-embedded images in a document, you can use the following methods:
one
Console.table ($$('img:not ([src ^ = data])'), ['src',' alt'])
In addition, when you use Markdown to generate HTML, most page generators create an automatic ID on the title, for example, the # New Stuff title becomes New stuff. If I need to batch create a lot of URL pointing to these anchor points, but don't want to do these things manually, I might need to script through the console to do this for me:
one
two
three
four
five
six
seven
eight
nine
Let out =''
$('# main [id]'). Filter (
Elm = > {return elm.nodeName.startsWith ('H')}
) .forEach (elm = > {
Out + = `$ {elm.innerText}
${_ document.location.href} # ${elm.id}
`
});
Copy (out)
The result is a block of text, with the text content of each title followed by a complete URL that points to the title.
An interesting extra feature of the $$shortcut is shown here. Document.querySelectorAll ('# main [id]'). Filter () causes an error because the value returned is not an array but a NodeList. You need to use [. Document.querySelectoAll ('# main [id]'). Filter ()] or Array.from (document.querySelectoAll ('# main [id]'). Filter () method to force it into an Array, which has bothered developers who transferred from jQuery to JavaScript for quite a long time, while with $, you can use all Array methods directly.
In general, you can change all the elements in the browser page through the console. And you have the added benefit of using the elements tab of DevTools to get all the page paths of the elements. Click next to each element. Menu and select the path you want to copy from the pop-up context menu.
Although the console itself is easy to use, you will soon find that Console has many difficulties in writing code. For example, Console is an one-line environment, which will be executed immediately after accidentally clicking Enter. But at the end of this article, you can use Shift + Enter instead of writing multi-line scripts.
Sources
Overall, Console is a good testing environment, but it is poor for the editing experience. Fortunately, however, there is a complete editor in the Sources panel. There, you can check the code of the current page and write more complex scripts to interact with it.
In addition to clicking the tab menu above, DevTools also has a set of shortcut keys Command Menu for you to use, which you can access by pressing control + shift + P (Windows, Linux) or Command+Shift+P (macOS). Or choose (. Or ⋮) menu, select "Run command".
Snippets code snippet
Snippets is a small piece of code that you have written that can significantly improve the efficiency of development. Click the Command Menu keyboard shortcut in DevTools, type snip and press enter, and select create a new snippet, which will take you to the Snippets editor, as shown below:
The form on the right includes a complete source editor with keyword coloring, automatic completion, multi-cursor and other functions. Let's start with the above example:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
twenty-one
twenty-two
twenty-three
twenty-four
twenty-five
twenty-six
twenty-seven
twenty-eight
twenty-nine
thirty
thirty-one
thirty-two
thirty-three
thirty-four
thirty-five
thirty-six
thirty-seven
thirty-eight
thirty-nine
forty
forty-one
forty-two
Console. Clear ()
Let out =''
Let problems = []
$('a') .forEach (a = > {
Let text = a.innerText.trim ()
Let prefix =''
If (! text) {
If (a.querySelector ('img')) {
Text = a.querySelector ('img'). Alt
Prefix = 'Image:'
}
If (a.getAttribute ('aria-label')) {
Text = a.getAttribute ('aria-label')
Prefix = 'Aria Label:'
}
If (a.getAttribute ('aria-labelledby')) {
Text = $('#'+ a.getAttribute ('aria-labelledby')) .innerText
Prefix = 'Aria Labelled By:'
}
}
If (text) {
Text = prefix + text
} else {
A.style.border = '1px solid firebrick'
Problems.push (a)
}
Out + = `
${text | |'No Link text'}
${a.href} `
});
If (out = =) {
Console.warn ('Sorry, no links found')
} else {
Copy (out)
Console.info ('done harvesting links, ready to paste')
If (problems.length > 0) {
Console.warn ('There were d issues:', problems.length)
Console.groupCollapsed ('Links without text')
Problems.forEach (a = > {console.dirxml (a)})
Console.groupEnd ('Links without text')
}
}
The following is an executive demo:
Overrides
Override implements local tests to replace server files by modifying the local copy of the remote file. For example, you can edit a complete complex stylesheet locally, but you don't have to wait for a lengthy re-build and deployment process to see the effect, which is a quick way to find problems during the development phase.
Integrate developer tools with VS Code
You can get developer tools in editing by installing the Microsoft Edge Tools for VS Code extension, and you can see the basic usage in the following figure.
This is the end of the content of "what is the use of the console"? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.