The implementation principle of let-var in for loop

1, the var

   for(var i = 1; i<=3; i++) {
      setTimeout(function(){
        console.log(i)
      }, 1000)}Copy the code

Result 4,4,4

Analysis: Each time the loop is executed, setTimeout is assigned to the timer module. After 1 second, the task is put into the asynchronous queue. The closure also saves the current execution context (global I). Log (I); console.log(I);

2, let

   for(let i = 1; i<=3; i++) {
      setTimeout(function(){
        console.log(i)
      }, 1000)}Copy the code

Result 1, 2, and 3

Analysis: Each time the loop is executed, setTimeout is assigned to the timer module. After 1 second, the task is placed in the asynchronous queue. The closure also saves the current execution context (I in the block level scope at this time). After the synchronization task is completed, the main thread executes three asynchronous tasks in the queue console.log(I)

Second, sorting,

   const lessons = [{title: 'a'.click: 10.price: 100}, {title: 'b'.click: 100.price: 1000}, {title: 'c'.click: 110.price: 1100}]
   function order(field, type="asc") {
     return function(a,b){
       if(type === 'asc') {
         return a[field] > b[field] ? 1 : -1;
       } else {
         return a[field] > b[field] ? -1 : 1; }}}let result = lessons.sort(order('price'.'asc'));
  // let result = lessons.sort(order('price', 'des'));
  // let result = lessons.sort(order('click', 'asc'));
   console.table(result);
   
Copy the code