1. Timed output 0,1,2

Modify the following code so that the timer outputs 0,1,2 in sequence

for (var i = 0; i < 3; i++) {
  console.log('gsy--0', new Date().getTime(),i)
  setTimeout(() => {
    console.log('gsy---1', new Date().getTime(),i) 
  }, 1000);
}
Copy the code

for (let i = 0; i < 3; i++) {
  console.log('gsy--0', new Date().getTime(),i)
  setTimeout(() => {
    console.log('gsy---1', new Date().getTime(),i) 
  }, 1000);
}
Copy the code

for (let i = 0; i < 3; i++) {
  console.log('gsy--0', new Date().getTime(),i)
  setTimeout(() => {
    console.log('gsy---1', new Date().getTime(),i) 
  }, i*1000);
}
Copy the code

May refer to

Task queue – event pool

The new Queue (). The task (1000, () = > console. The log (1)). The task (2000, () = > console. The log (2)). The task (3000, () = > console. The log (3)). The start () to implement this function, After start(), wait 1 second to output 1, wait another 2 seconds to output 2, and wait another 3 seconds to output 3.Copy the code
  • The chain call to Promise’s then
  • The chain call returns this

The Class writing

class Queue {
  constructor() {
    console.log('gsy---constructor', new Date().getTime())
    this.queue = []
  }
  task(times, cb) {
    this.queue.push({
      times,
      cb
    })
    console.log('gsy---task', this.queue)
    return this
  }
  async start() {
    let result = Promise.resolve()
    while (this.queue.length > 0) {
      const {
        times,
        cb
      } = this.queue.shift()

      result = result.then(() => {
        console.log('gsy---then', new Date().getTime())
        return new Promise((resolve) => {
          setTimeout(() => {
            cb();
            console.log('gsy---resolve', new Date().getTime())
            resolve()
          }, times)
        })
      })
      console.log('gsy---result', new Date().getTime())
    }
  }
}

new Queue()
  .task(1000, () => {
    console.log(1)
  })
  .task(2000, () => {
    console.log(2)
  })
  .task(3000, () => {
    console.log(3)
  })
  .start()
Copy the code

ES5

function Quene() {
  this.quene = [];
}

Quene.prototype.task = function (time, callback) {
  this.quene.push({
    time,
    callback
  });
  return this;
};

Quene.prototype.start = function () {
  const quene = this.quene;
  let result = Promise.resolve();
  quene.forEach((item) => {
    result = result.then(() => {
      console.log('gsy---then', new Date().getTime())
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(item.callback());
          console.log('gsy---resolve', new Date().getTime())
        }, item.time);
      });
    });
    console.log('gsy---result', result)
  });

  return result;
};


new Quene()
  .task(1000, () => {
    console.log(1)
  })
  .task(2000, () => {
    console.log(2)
  })
  .task(3000, () => {
    console.log(3)
  })
  .start()
Copy the code
  • Async await time stacking (not recommended)
async function one() {
  console.log('gsy---0', new Date().getTime())
  setTimeout(function () {
    console.log(1);
    console.log('gsy---setTimeout', new Date().getTime())
    }, 1000);
}
async function two() {
  console.log('gsy---0', new Date().getTime())
  setTimeout(await
    function () {
      console.log(2);
      console.log('gsy---setTimeout', new Date().getTime())
    }, 3000);
}
async function three() {
  console.log('gsy---0', new Date().getTime())
  setTimeout(await
    function () {
      console.log(3);
      console.log('gsy---setTimeout', new Date().getTime())
    }, 4000);
}
async function run() {
  var p1 = await one();
  var p2 = await two();
  var p3 = await three();
}
run();
Copy the code

3. Prototype chain and this

  • Window. The name assignment

Window.name is a default window property of type “string” and its type cannot be changed. That is, if a value is assigned to it, the value must be of type string, otherwise the toString method of the value will be called automatically to convert the value toString.

  • The body of the function
  • call
// The output is string typeof window.name // Change its type to number window.name = 100 // Still output is string typeof window.nameCopy the code
window.name = 10
function Foo() {
  this.name = 'bar'
}
Foo.prototype.getName = ()=> {
  console.log(this)
  return this.name+1
}
let foo = new Foo();
let getName = foo.getName;

console.log(getName)
// // ()=> {
//   debugger
//   console.log(this)
//   return this.name+1
// }
console.log(getName())
// window 
// 101
console.log(getName.call(Foo))
// window 
// 101
Copy the code
function Foo() {
  getName = function(){ console.log(1); };
  return this;
}
Foo.getName = function() { console.log(2); };
Foo.prototype.getName = function(){ console.log(3); };
var getName = function() { console.log(4); };
function getName(){ console.log(5); }

Foo.getName(); //
getName(); //
Foo().getName(); //
getName(); //
new Foo.getName(); //
new Foo().getName(); //
Copy the code

4, ‘abbbaca’=>’ aACA ‘=>’ca’

  • Stack on stack on stack
  • The pointer moves to a different position
  • Static method of string length
//// 'abbbaca'=>' aACA '=>'ca' /** * Remove adjacent characters that appear more than = 2 times * @param {string}s */ let removeDuplicate =(s) =>{const stack  = [] // Space: O(n) let top let next let i = 0 while (i < s.length) { // Time: O(n) top = stack[stack.length-1] next = s[I] if (next === top) { // 2. Move pointer, Pop () while (s[I] === top) I += 1} else {stack.push(next) I += 1}} return stack.join(" ") // Time: O(n) } let s = 'abbbaca' let b = removeDuplicates(s) console.log(b)Copy the code
  • No pointer movement
// 'abbaca'=>'aaca'=>'ca'
// 'abbbaca'=>'abaca'
var removeDuplicates = function(S) {
  let stack = [S[0]]
  for (let i = 1; i < S.length; i++) {
    if (S[i] === stack[stack.length - 1]) {
      stack.pop()
    } else {
      stack.push(S[i])
    }
  }
  return stack.join('')
};
let s = 'abbbaca'
let b = removeDuplicates(s)
console.log(b)
Copy the code
//// 'abbbaca'=>'aaca'=>'ca' let s = 'abbbbaca' const removeDuplicates = function (s) { let arr = s.split('') let newArr  = arr while (quDouble(newArr).flag) { newArr = quDouble(newArr) } return newArr.arr.join('') }; function quDouble(arr) { debugger let minidx = 0 let flag = false for (let i = 0; i < arr.length; i++) { minidx = i let j = i while (arr[i] === arr[j + 1]) { flag = true; j++ } if (i ! == j) { arr.splice(i, j-i+1) } } return { arr: arr, flag: flag }; } let newString = removeDuplicates(s) console.log(newString)Copy the code

5, cross-domain