banner
DIYgod

Hi, DIYgod

写代码是热爱,写到世界充满爱!
github
twitter
follow
bilibili
telegram
email
steam
playstation
nintendo switch

Baidu Front-end Technology Academy Coding Challenge (TASK 0002)

TASK 0002 has been released, the task time for the beginner class is from April 24 to May 7, and for the intermediate class from April 18 to April 25.

TASK 0002 content: https://github.com/baidu-ife/ife/tree/master/task/task0002

What I did: https://github.com/DIYgod/ife-work/tree/master/task0002

Online Demo: https://www.anotherhome.net/file/ife/task0002/task0002_1.html

This task took a total of 17 days (4.19-5.6)

Below are some records from my process of doing TASK 0002.


1. JavaScript Performance Optimization (Reference JavaScript Performance Optimization: Loading and Execution)

  • Web developers generally load external JavaScript in the <head> and then use <link> tags to load external CSS files or other page information. However, this conventional approach hides serious performance issues—scripts block the download of other resources on the page. Therefore, it is recommended to place all <script> tags as far down as possible in the <body> tag to minimize the impact on the overall page download.

  • Since each <script> tag blocks page rendering during initial download, reducing the number of <script> tags included in the page helps improve this situation.

  • Other methods to reduce the impact of JavaScript on performance can be found in the references.

 

2. == vs === (Reference The Difference Between Double Equals "==" and Triple Equals "===" in JavaScript The Difference Between Three Equals and Two Equals in JavaScript JavaScript Coding Standards)

==: equality operation, but does not compare the type of values;
===: strict equality operation, which compares both value and type, returning true only if both are the same.

The Baidu JavaScript coding standards also stipulate: in Equality Expressions, strictly use the type-strict ===. Only when checking for null or undefined is == null allowed. This is because using === can avoid implicit type conversion in equality checks.

 

3. Type Detection (Reference JavaScript Coding Standards JavaScript Array Type Detection: Writing a More Robust isArray Function Perfect Solution for JavaScript Function Type Detection)

General simple approach: use typeof for type detection. Use instanceof for object type detection. Use == null for detecting null or undefined.

To determine array type: get the string representation of the object and compare whether this string is '[object Array]'

Updated on 9.20: This can also be done

To determine function type: first ensure that the object being tested exists, and serialize it into a string containing "function", which is the basis for our detection (fn.constructor != String, fn.constructor != Array, and fn.constructor != RegExp). Additionally, we need to ensure that the declared function is not a DOM node (fn.nodeName). Then we can perform a toString test. If we convert a function to a string in a browser (fn + ""), the result will look like this: "function name(){...}". Now, determining if it is a function is simple, we just need to check if the string contains the word "function". This is amazing, as for any problematic function, we can get the required result in all browsers. This function is somewhat slower than traditional methods, and the author (John Resig) suggests using it conservatively.

Updated on 9.20: The above method is too complicated; it can be determined similarly to Array.

Simple way to copy Array:

 

4. Type Conversion (Reference JavaScript Coding Standards)

number -> string:

string -> number:

-> boolean:

number remove decimal point:

 

5. Cache length when iterating over ordered collections (Reference JavaScript Coding Standards)

Although modern browsers cache the length of arrays, for some host objects and older browser array objects, the number of elements is dynamically calculated on each length access. In this case, caching the length can effectively improve program performance.

 

6. The Pitfalls of document.body.scrollTop and document.documentElement.scrollTop for Getting Scroll Distance (Reference Compatibility of document.body.scrollTop and document.documentElement.scrollTop Using JavaScript to Get the Position of Page Elements Issues with document.body.scrollTop and document.documentElement.scrollTop in Firefox, Chrome, and IE where the value is 0)

Based on Ruan Yifeng's tutorial, I wrote the following:

Unexpectedly, I encountered a pitfall, and the result elementScrollLeft is always 0. The debugging result is as follows:

task0002_1

What a pitfall! It was said that if there is a document declaration (i.e., the first line of the webpage is docType), the value of document.compatMode equals "CSS1compat", and standard browsers only recognize documentElement.scrollTop.

Additionally, I tried IE and Firefox, both of which recognize documentElement.scrollTop, but Chrome is wrong!

Fortunately, document.body.scrollTop and document.documentElement.scrollTop have a characteristic: only one value will be effective at a time. For example, when document.body.scrollTop can obtain a value, document.documentElement.scrollTop will always be 0; and vice versa. So it can be written like this:

 

7. Get All DOM Elements

Suddenly had a brainwave

 

8. Truthiness Check

Objects are always true, basic types check for emptiness

It's easy to mistakenly think an empty array is false!

It's easy to mistakenly think an empty array is false!

It's easy to mistakenly think an empty array is false!

Important things should be said three times!

 

9. Recursively Get All Child Elements

This has a problem; it can only get the first level of child elements:

But if changed like this, it can get all child elements:

The reason for the problem in the first piece of code is unknown; I have thought about it for a whole night with no progress.

Additionally, during debugging, I discovered a strange phenomenon:

task0002_2

To explain: the return value allchilds during the recursive call is correct, but when returning to the previous level, it was not added to the allchilds of the previous level.

月月 told me that this line has a problem!

W3School states: the concat() method is used to join two or more arrays.
This method does not change the existing arrays but returns a copy of the joined arrays. It only returns a copy of the joined arrays. It only returns a copy of the joined arrays.

Everything makes sense now...

So it has nothing to do with the position of the allchilds declaration; the direction of debugging has always been wrong. It should be changed like this:

I never expected that, with the help of 月月 李胜 蛋炒饭 I finally completed this small function...

Subsequently: I suddenly thought that this way I can easily get

I am spitting blood

 

10. Array Merging (Reference JavaScript concat() Method)

Important things should be stated separately. Because I was severely misled.

The concat() method is used to join two or more arrays.

This method does not change the existing arrays but returns a copy of the joined arrays.

This method does not change the existing arrays but returns a copy of the joined arrays.

This method does not change the existing arrays but returns a copy of the joined arrays.

Incorrect usage:

Correct usage:

 

11. Event Delegation (Reference JavaScript Event Delegation)

In programming, if we do not want or cannot directly manipulate the target object, we can use delegate to create a proxy object to call the methods of the target object, thus achieving the purpose of manipulating the target object. Undoubtedly, the proxy object must have a reference to the target object.

We can elegantly use an event delegation method to proxy one function with another function, for example:

This way we can elegantly use on and un functions to proxy addEvent and removeEvent functions. This achieves the hiding of the target object, which is very useful for protecting some core objects.

I was wrong; it can be done directly like this...

 

 

12. Object Related (Reference What Exactly is the Object in JS?)

Array, Boolean, Date, Function, Number, and other objects actually all come from Object; they all have Object as their ancestor. They exhibit different language features, such as Array having an automatically managed length property, Boolean only having true or false values, Date representing time structures, and Function being executable, all of which are capabilities granted to them by their primitive types (valueOf).

So here are some interesting things:

You can set a property of a function to be another function.

 

13. JavaScript Regular Expression Grouping (Reference JavaScript Regular Expressions: Choices, Grouping, and References)

Example:

Where re.exec(document.cookie) is an array, the first element is all characters matched by the regular expression, and the second element is the first group matched, i.e., the content in the first parentheses: (.*?)

Grouping refers to sub-expressions in regular expressions, which can be used to obtain specific parts of the string matched by the regular expression.

Updated on 9.20: When creating a regular expression object using a constructor, the usual character escape rules (adding a backslash \ in front) are required. For example, the following are equivalent:

 

14. JavaScript Cross-Domain (Reference Summary and Solutions for JavaScript Cross-Domain Issues)

JavaScript does not allow cross-domain calls to objects of other pages for security reasons. However, this security restriction has also caused a lot of trouble for injecting iframes or ajax applications.

Specific restrictions and solutions can be found in the references.

 

15. JavaScript Months Off by One (Reference Why is there an Extra Month in new Date in JS? JavaScript—Problems Encountered When Using Date Objects for Gantt Charts)

task0002_4

Clearly set to May, but the result is June.

In reality, we count months starting from 1, but JavaScript starts from 0. Month 0 in JS is January for us, month 1 in JS is February...

So remember to subtract one when setting the month and add one when getting the month.

 

15. Timers Do Not Block Code Execution

task0002_5

My intention was to execute a() and then output b, but unexpectedly b was output first. From this, it can also be inferred that timers do not block the execution of subsequent statements.

 

☆ミ(o*・ω・)ノ End of the review waiting for review

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.