Continuous learning is essential if you want to stay a programmer.

People usually prefer a team with a better technical atmosphere when looking for a job, because it can help them grow better, but not every team has such an atmosphere. So the idea came up that I wanted to build a place where some people could record what they learned. This will often be a small dot and may not be enough to write an article. However, this knowledge may not be known by many people, so it is a great thing to let others learn this knowledge through this way of recording.

If you want to be a part of this record, you are welcome to contribute, the address is here.

In all, 55 people contributed what they learned this week. Here’s a round-up of what they learned.

JS

Solve the keyboard pop-up back block form problem

window.addEventListener('resize'.function () {
if (
  document.activeElement.tagName === 'INPUT' ||
  document.activeElement.tagName === 'TEXTAREA' ||
  document.activeElement.getAttribute('contenteditable') = ='true'
) {
  window.setTimeout(function () {
    if ('scrollIntoView' in document.activeElement) {
      document.activeElement.scrollIntoView();
    } else {
      // @ts-ignore
      document.activeElement.scrollIntoViewIfNeeded(); }},0); }})Copy the code

Image loading correlation

The first is to achieve lazy image loading

<ul>
	<li><img src="./img/default.png" data="./img/1.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/2.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/3.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/4.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/5.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/6.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/7.png" alt=""></li>
	<li><img src="./img/default.png" data="./img/8.png" alt=""></li>
</ul>Let imgs = document. QuerySelectorAll (' img ') / / window visual zone height let clientHeight = window. The innerHeight | | document.documentElement.clientHeight || document.body.clientHeight; Imgs [I].getBoundingClientRect(). Top function lazyLoadImg () {for (let I = 0; i< imgs.length; i{+ +)if((imgs[i].getBoundingClientRect(a).top + imgs[i].height) >=0&&imgs[i].getBoundingClientRect().top < clientHeight) {imgs[i].src = imgs[i].getAttribute('data')}}}window.addEventListener('scroll', lazyLoadImg);
Copy the code

However, this method will cause a flash of white during the image download process, which can be solved by preloading the image with JS.

At the same time, the lazy loading solution mentioned above is very old, and the latest API Intersection_Observer can be used to do this, which is simpler and more controllable.

None loop Generates an array of specified length

const List1 = len= > ' '.padEnd(len, ', ').split('. ')

const List2 = len= > [...new Array(len).keys()]
Copy the code

When is the callback to the asynchronous Promise’s then method added to the MicroTasks queue?

Today, I saw a question on my blog:

const pro = new Promise((resolve, reject) = > {
    const pro1 = new Promise((resolve, reject) = > {
        setTimeout((a)= > {
            resolve(3);
        }, 0);
    });
    resolve(4);
    pro1.then((args) = > {
        console.log(args);
    });
});
pro.then((args) = > {
    console.log(args);
});
Copy the code

Many of you know that the output of this problem is 4,3; However, I have A big question about this question, because I have not started to implement the promise that conforms to the promise A/A+ plan. Therefore, every time I do this kind of question, I rely on my usual use experience. In fact, I feel very empty in my heart, and then I check the spec by myself: ECMAScript 2018 Language Specification According to the spec, if a promise is pending when called then, The callback will enter the promise of [[PromiseFulfill/RejectReactions]] list; Otherwise it goes to PromiseJobs.

PromiseJob and Job Queue are in ES, macroTask and microTask are in browsers, and setTimeout is also provided by the host environment. So output 4 3 is the result of constraints shared by both ECMAScript and browser specifications.

PromiseJob corresponds to a microTask in the browser. If the promise is pending when then is called, the callback goes to the reactions queue. When the promise is FULFILL or reject, flush the reactions queue, Each reaction corresponds to a PromiseJob enqueue to Job Queue if the promise is in the other two states when you call then, The JS engine simply enqueue a corresponding PromiseJob into the code in the Job Queue example.

In the following order:

0. Current cycle of evevt loop start Timer get enqueued 2. Resovle pro, because there is no fulfillReaction binding to pro,do nothing
3. call then() at pro1, because pro1 is pending, add fulfillReaction to pro1
4. call then() Because pro is reolved, immediately enqueue a PromiseJob 5. current macroTask is finished 6. run all PromiseJobs(microTasks)inorder, 7. console.log(4) 8. current cycle of event loop is finishedanother cycle starts 9. Timer Fires, And pro1 is fulfillments 10. At this time, pro1 hasfulfillments, enqueue every reaction as a PromiseJobin order
11. current macro Job is finished 
12. run all PromiseJobs in order
13. console.log(3)
14. current cycle of event loop is finished
Copy the code

Open the specified App or download the App on the mobile terminal

navToDownApp() {
      let u = navigator.userAgent
      if (/MicroMessenger/gi.test(u)) {
        // If it is opened on wechat client, guide the user to open it in browser
        alert('Please open it in your browser')}if (u.indexOf('Android') > - 1 || u.indexOf('Linux') > - 1) {
        // Android
        if (this.openApp('en://startapp')) {
          this.openApp('en://startapp') // Open the specified APP through the Scheme protocol
        } else {
          // Jump to Android download address}}else if (u.indexOf('iPhone') > - 1) {
        if (this.openApp('ios--scheme')) {
          this.openApp('ios--scheme') // Open the specified APP through the Scheme protocol
        } else {
          // Jump to IOS download address
        }
      }
    },
    openApp(src) {
      // Try to open the APP by iframe. If the APP can be opened normally, it will switch directly to the APP and automatically block the default behavior of the A tag
      // Otherwise open the href link for the A tag
      let ifr = document.createElement('iframe')
      ifr.src = src
      ifr.style.display = 'none'
      document.body.appendChild(ifr)
      window.setTimeout(function() {
        // Open App and remove iframe
        document.body.removeChild(ifr)
      }, 2000)}Copy the code

Parse the URL using the A tag

function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/ ^ \? /.' ').split('&'),
                len = seg.length, i = 0, s;
            for(; i<len; i++) {if(! seg[i]) {continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            returnret; }) (),hash: a.hash.replace(The '#'.' ')}; }Copy the code

Array to heavy

  var array = [1.2.1.1.'1'];
  function unique(array) {
    var obj = {};
    return array.filter(function(item, index, array){
      return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})}Copy the code

Using an empty Object, we store the value of the array as the key value of Object, such as Object[value1] = true. If Object[value2] exists in another value, the value is duplicate.

Since 1 and ‘1’ are different, this method evaluates to the same value because the key of the object can only be a string, so we can avoid this problem by using typeof item + item as the string key

JS function object parameterstrap

Last week, when implementing a shell layer function, we used the contains method function in RC-util. Results in code-review, colleagues raised questions about this code:

Rc-util source repository

export default function contains(root, n) {
  let node = n;
  while (node) {
    if (node === root) {
      return true;
    }
    node = node.parentNode;
  }
  return false;
}
Copy the code

The code above is a tool method of antD’s internal abstraction to determine whether a DOM is an ancestor node of another DOM.

Let node = n; Is this code redundant?

The first understanding is that the function argument n is an object, a DOM node object. If you use node to store the value of n, this prevents node = node.parentNode from changing the value of the passed argument n.

After all, we’re all familiar with the following code:

function contains(root, n) {
  if(n) {
    n.a = 3}}const A = {a:1};
const B = {a:2};
contains(A,B)
console.log(B)    // {a:3}
Copy the code

That is, when an argument is an object, the value of that object can be changed inside the function to affect arguments outside the function.

But test another piece of code and find it is not the same as understood:

function contains(root, n) {
  if(n) {
    n = {a:3}}}const A = {a:1};
const B = {a:2}
contains(A,B)
console.log(B) // {a:2}
Copy the code

N.a = 3 and n = {a:3} are different.

When the function is first executed, n is a reference to the argument B.

N.a = 3 is associated with a reference to the same reference as B, so it changes the value of the argument B.

N = {a:3} points to a new object {a:3} instead of the argument B, so that n is completely disconnected from B and therefore does not change the value of B.

Is it possible to make an issue to the ant team and suggest deleting this code, but there will be no bugs with this code

Related information: JavaScript deep parameter passing by value

other

Kill Specifies a port

The following command can kill port 8080, or you can use the NPM command to specify the port to be killed.

lsof -i tcp:8080 | grep LISTEN | awk '{print $2}'| awk -F"/" '{ print $1 }' | xargs kill9 -Copy the code

In addition, the above commands are not available on Windows. If you need multiple platforms, you can use kill-port-process directly.

Replace text on the command line in Linux

# replace the I tag of the WXML file with text
grep '<i ' -rl . --include='*.wxml' --exclude-dir=node_module --exclude-dir=dist | xargs sed -i -e 's/<i /<text /g'
grep '</i>' -rl . --include='*.wxml' --exclude-dir=node_module --exclude-dir=dist | xargs sed -i -e 's/<\/i>/<\/text>/g'
Copy the code

How to determine whether the newline character in a file is LF(\n) or CRLF(\r\n)

Article link, through this article to learn what a newline character is.

In addition, the big guy every day to learn the knowledge recorded down, interested can read.

Half a year after graduation

  • Their own strength is the most important, to have a core skills, other aspects also have to dabble.
  • The impact of the company on individuals is great, if a company is not willing to cultivate you, it is not worth paying.
  • Communication is really important, and unclear communication can lead to a whole host of problems.
  • Speaking is an acquired skill. Communicate with others and keep your mouth shut.
  • Don’t hate overtime, the gap between people a few hours after work, overtime can learn ah. Lei Jun also said that you take 3000 yuan for my youth for a month, more than not cost-effective.

The last

This week’s posts were of high quality and I learned something from them.

This is something that needs to be shared to be sustainable, and I can’t do it alone. Everyone is welcome to participate in this event. The address is here.