preface

Great oaks from little acorns rise, brick by brick. I think it’s going to be a wave of 36 handwritten JS questions

Three JS handwritten questions

Data type judgment

Basic knowledge:

  1. Js data types are divided into base types and reference types. Base types: Number, Null, Undefind, String, BigInt, Boolean, Symbol. Reference types: Date, RegExp, Array, Function, Math.Copy the code
  2. 2. Typeof judgment data type in js: Typeof can recognize the underlying data type + function (but not Null) (typeof Null) return "object" although typeof Null will output object, this is a long-standing JS Bug, Null does not refer to a data type, and null itself is not an object. Instanceof: If we create a new object, then the new object is the object from which it inherits its prototype chain. Using instanceof, we can determine whether this object is the object generated by the previous constructor, and thus basically determine the data type of this new object. Object. The prototype. ToString: toString () method was the prototype of the Object, and call the method, can be unified return string format for "[Object] Xxx", where Xxx is the type of the Object. For Object objects, toString() returns [Object Object]; Other objects need to be called by call to return the correct type information.Copy the code

Determine the data type by hand (return Boolean or function)

function myTypeof(obj) {
    let datatype = Object.prototype.toString.call(obj)
    / / or
    // datatype = datatype.slice(8, -1).toLowerCase();
    // Let's use the toString method on the Object prototype
    // Apply in the context of the obj passed in (call this to obj)
    datatype = datatype.split(' ') [1]
    // Split the array with split and take the second item of the array
    datatype = datatype.splice(0, datatype.length-1).toLowerCase()
    return datatype;
}
Copy the code

Js inheritance methods

The first type of prototype chain inheritance

function Parent1() {
    this.name = 'parent1';
    this.play = [1.2.3]}function Child1() {
    this.type = 'child2';
  }
  Child1.prototype = new Parent1();
Copy the code

The second constructor inheritance

function Animal(name) {
    this.name = name;
    this.getName = function() {
        return this.name; }}function Dog(name) {
    Animal.call(this, name);
}
let a = new Dog('human beings');
console.log(a.getName());
Copy the code

But because methods must be defined in constructors, this results in the method being created every time an instance of a subclass is created.

The third kind of combinatorial inheritance

function Animal(name) {
    this.name = name;
    this.colors = ["White"."Black"];
}
Animal.prototype.getName = function() {
    return this.name;
}
function Dog(name, age) {
    Animal.call(this, name);
    this.age = age;
}
// Dog.prototype = new Animal()   
/ / side effects will put the Dog. The prototype. The constructor Cat into Animal
// Dog.prototype.constructor = Dog;
// Or directly
Dog.prototype.__proto__ == Animal.prototype;
console.log(Dog.prototype.constructor,'oooooooo');
let dog1 = new Dog('shake'.2)
dog1.colors.push('pink')

let dog2 = new Dog('huang'.1);
dog2.colors.push('Silver white');
console.log(dog2)
Copy the code

The fourth type of parasitic inheritance

function clone (parent, child) {   
   // Parasitic inheritance uses object.create ()
    // This method takes two arguments: an object to be used as a prototype for the new object
    // An object that defines additional attributes for the new object (optional)
    // Use object.create to reduce the need for multiple constructs in composite inheritance
    child.prototype = Object.create(parent.prototype);
    // child.prototype.__proto__ -> parent.prototype
    child.prototype.constructor = child;
  }
function Parent6() {
  this.name = 'parent6';
  this.play = [1.2.3];
}
  Parent6.prototype.getName = function () {
  return this.name;
}
function Child6() {
  Parent6.call(this);
  this.friends = 'child5';
}
clone(Parent6, Child6);
Child6.prototype.getFriends = function () {
  return this.friends;
}
let person6 = new Child6();

console.log(person6);

console.log(person6.getName());

  console.log(person6.getFriends());
Copy the code

The fifth extends inheritance


class Animal {
    constructor(name) {
        this.name = name
    } 
    getName() {
        return this.name
    }
}
class Dog extends Animal {
    constructor(name, age) {
        super(name)          
        // super refers to the prototype of the current object, which is Animal
        this.age = age
    }
}

Copy the code

Array to heavy

The first is to borrow a filter

function unique(arr) {
    The filter() method creates a new array,
    // The elements in the new array are checked by checking all the elements in the specified array
    var res = arr.filter(function(item, index, array) {
        // console.log(array, 'array');
        return array.indexOf(item) === index
    })
    // item is required. The value of the current element
    // index Optional. The index value of the current element
    // array Optional. The array object to which the current element belongs
    return res
} 
Copy the code

The second borrows reduce

function unique1(arr) {
    let un = arr.reduce((pre,cur) = >{
        if(! pre.includes(cur)) { pre.push(cur) }return pre
    },[])
    return un
}
Copy the code

The third Set structure

function unique2(arr) {
    return [...new Set(arr)]
    // Set is also a constructor whose data structure is similar to that of an array,
    // The difference is that there is never a duplicate value.
    // add(value) : Adds a value, returns the Set structure itself.
    // delete(value) : deletes a value and returns a Boolean value indicating whether the deletion was successful.
    // has(value) : Returns a Boolean value indicating whether the value is a member of Set.
    // clear() : clears all members with no return value.
}
Copy the code

The fourth Map structure

function unique3(arr) {
    let map = new Map(a);console.log(map)
    //let arr1 = new Array(); // The array is used to return the result
    let arr1 = []
    for (let i = 0, len = arr.length; i < len; i++) {
        if (map.has(arr[i])) {      // Check whether the key exists
            map.set(arr[i], true);
        }
        else {
            map.set(arr[i], false);
            arr1.push(arr[i]);
        }
    console.log(map)
    }
    return arr1;
}
Copy the code

The latter

Object this JS handwriting problem can first look at the problem, and then start to write the relevant code.