Sophomore Examination Summary

Topic 1:

 1.typeof(typeofA);
    2.typeof({})
    3.typeof(null)
    4.(false=='')
    5.(NaN==NaN)
    6.(null==undefined)
    7.(null===undefined)
    8.(0=='')
    9.("20"+20)
    10.(10+10+"20")

The result is 1.String 2.object 3.object
4.true will have a cast to convert''to false
5.false non-numbers are not equal to any value
6. true
7.False ===means absolute equal
8. true
9.2020 is a string

10.2020 is also a string

Differences between call, apply and bind

All three of them can make changes to this point, the parameters passed in the call are comma-separated, the parameters passed in the apply are passed in as arrays, but although bind can also change this point, its return value is a function that changes this point, and the function will not execute immediately, and () is needed to execute it.

Write out the following output and modify it to output 1, 2, 3, 4, 5

function x() {
const result = [];
for (var i = 0; i < 5; i++) {
    result[i] = function y() {
        console.log(i);
    };
}
return result;
}
const functions = x();
for (let j = 0; j < functions.length; j++) {
    functions[j]();   
};

Output result: 5 5 5 5 5
Method 1:

function x() {
    const result = [];
    for (var i = 0; i < 5; i++) {
        result[i] = (function y() {
            console.log(i + 1);
        }(i));
    }
    return result;
}
const functions = x();

Method 2:

// console.log("Hollow Node!!!");
function x() {
    const result = [];
    for (var i = 0; i < 5; i++) {
        setTimeout(function (i) {
            return function () {
                console.log(i + 1);
            }
        }(i), 1000);
    }
    return result;
}
const functions = x();

Relevant knowledge:
Var:var is generally defined as a global variable, the function is executed to find the value of I in the global scope. In the above question, the value of I changes until the last cycle is i=5. When the function executes, it looks for the value of I in the global variable, so it prints out five 5
Let:let declares variables that are valid only in the block-level scope in which they are located, and let keywords have no variable elevation. In this topic, you can print 1, 2, 3, 4, 5 by converting lvar to let. Since let declarations are block-level variables, the following letters will all go back to their blocks to find the value of i at that time, and then print.
There is no variable promotion for const:const, but there will be a block-level scope, but the original data in it cannot be modified, but the data in the reference value can be modified, but the address cannot be changed.

Write out the output of the following code

console.log(v1)
  console.log(foo)
  var v1 = 100
  function foo() {
    console.log(v1)
    var v1 = 200
    console.log(v1)
  }
  foo()
  console.log(v1)

undefined function{ } undefined 200 100
Note: var a=100 variable declarations will increase, but assignments will only occur when this code is read. After a variable is raised, they are undefined until they are not assigned

  let a = 10
  var length = 11
  function fn() {
    console.log(this.a, this.length)
  }
  fn()
  let obj = {
      a: 5,
      length: 11,
      say: function() {
        console.log(this.a)
        fn()
        arguments[0]()
      }
  }
  obj.say(fn);

The result is: undefined 115 undefined 11 undefined 1
Note: The let keyword forms a block-level scope, and when fn() executes, this points to window, which can still be found in the block-level scope below the variable requested by var, but the variable requested by let must be passed in if it is to be found in the following scope, so it is undefined 11, obj.say (fn)When executing, first execute say in obj, this points to obj, so this.a is printed, fn() in say () is executed, this points to window, so it prints undefined 11, and I'm not sure why arguments[0] will form a closed thing after being called, but I don't know why its this points to itself.

 setTimeout(()=>{
  console.log('timeout');
  },0)
  new Promise((resolve) => {
    console.log('a')

    setTimeout(()=>{
      console.log('c');
    }, 0)
    resolve()
    console.log('b')
  }).then(() =>{
    console.log('promise');
  }).catch(() =>{
    console,.log('error');
  });
  console.log('code');

The result is:
a b code promise timeout c
Relevant knowledge: Here the browser will put some task tasks in the macro or micro queue. Before the tasks in the micro queue can be executed, the contents in the micro queue must be executed first.

Interpretation Using the constructor Person() as an example, the relationship between prototype, constructor and u proto_u is explained

Person constructors have prototype prototypes, prototype prototypes have a Person constructor pointed to by the constructor attribute, and object u proto_ attributes from Person constructor new are to Person's prototype, and there are constructors in the prototype pointing to the constructor.

js simple algorithm questions: the following objects are sorted by age, the same age by name. Output results

    person1={name:'jane',age:35}
    person2={name:'maru',age:23}
    person3={name:'harvey',age:21}
    person4={name:'anne',age:21}
let person1 = { name: 'jane', age: 35 },
    person2 = { name: 'maru', age: 23 },
    person3 = { name: 'harvey', age: 21 },
    person4 = { name: 'anne', age: 21 };
let arr = [person1, person2, person3, person4];
arr.sort((a, b) => {
    if (a.age != b.age) {
        return a.age - b.age;
    } else {
        if (a.name > b.name) {
            return 1;
        } else {
            return -1;
        }
    }
})

Note: Sort sort changes the original array, but it is ASCII sort.
When the return value is negative, the first number is in front, the last number is in front, and 0 is not moving.

Algorithmic problems

(1) js implements array unwrapping
Method 1: Double-layer cycle, outer-layer cycle elements, and inner-layer cycle to compare values.
If the value is the same, delete it
Note: After deleting the element, you need to reduce the length of the array by 1.

Array.prototype.distinct = function () {
    let arr = this;//Store the array to be processed with arr before proceeding
    let i, j, len = arr.length;
    for (i = 0; i < len; i++) {
        for (j = i + 1; j < len; j++) {
            if (arr[i] == arr[j]) {
                arr.splice(j, 1);//Delete from j th position, delete one
                len--;
                j--;
            }
        }
    }
    return arr;
}
let arr = [1, 2, 3, 4, 1, 1, 2, 3, 2, 5, 6];
let b = arr.distinct();
console.log(b);

Disadvantages: High memory consumption, slow speed
Method 2: Removing weights by taking advantage of different attributes of objects

Array.prototype.distinct = function (){
 var arr = this,
  i,
  obj = {},
  result = [],
  len = arr.length;
 for(i = 0; i< arr.length; i++){
  if(!obj[arr[i]]){ //If found, prove that the array element is duplicated
   obj[arr[i]] = 1;
   result.push(arr[i]);
  }
 }
 return result;
};
var a = [1,2,3,4,5,6,5,3,2,4,56,4,1,2,1,1,1,1,1,1,];
var b = a.distinct();
console.log(b.toString()); //1,2,3,4,5,6,56

Method 3: Use indexOf and forEach

Array.prototype.distinct = function () {
    var arr = this;
    var result = [];
    arr.forEach(value => {
        if (result.indexOf(value) == -1) {
            result.push(value);
        }
    })
    return result;
}
var a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 2, 2, 1, 23, 1, 23, 2, 3, 2, 3, 2, 3];
var b = a.distinct();
console.log(b.toString()); //1,23,2,3

Method 4: set using ES6
Set data structure, similar to an array, whose members have unique values. Convert the Set structure to an array using Array.from

let arr = [1, 1, 1, 2, 3, 1, 4, 6, 4, 6, 8];
let arr1 = new Set(arr);
arr = Array.from(arr1);
// console.log([...arr1]); //Converting Objects to Arrays by Expansion Operators
console.log(arr);

(2) Length of the last word
Give you a string s consisting of several words separated by some space characters. Returns the length of the last word in the string
Degrees.
Words are the largest substring that consists of only letters and does not contain any space characters.
There is at least one word in ps.string s

 Example 1: Input: s = "Hello World" 
 Output: 5 
 Example 2: Input: s = " fly me to the moon " 
 Output: 4 
 var lengthOfLastWord = function(s) { };
function endlen(str) {
    let flag = 0, reslut;
    for (let i = 0; i < str.length; i++) {
        if (str[i] != " ") {
            flag++;
        } else {
            flag = 0;
        }
        if (flag != 0) {
            reslut = flag;
        }
    }
    return reslut;
}
var str = "her hat is blank   ";
var result = endlen(str);
console.log(result);

Tags: Javascript

Posted on Thu, 09 Sep 2021 13:47:47 -0400 by Billett