js面试题(1)

45 阅读2分钟

1.值类型与引用类型有什么区别?

哪些类型是值类型?哪些类型是引用类型

  • 值类型:Strin、Number、Boolean、Symbol
  • 引用类型:JSON、Array、null

演示值类型与引用类型的堆栈模型

演示值类型与引用类型的堆栈模型1.png

演示值类型与引用类型的堆栈模型2.png

演示代码

 let a1 = 200;
 let b1 = a1;
 b1 = 20;
 console.log(a1); // 200

let a2 = {age : 20};
let b2 = a2;
b2.age = 2;
console.log(a1); // age : 2

2.深拷贝

如何实现深拷贝

  • JSON.parse(JSON.stringify(obj))

不能存放函数、时间对象、正则...

  • 递归

没有考虑循环引用。。

  • lodash.cloneDeep 推荐,工作中没必要重复造轮子

演示代码

   const obj1 = {
        name: "张三",
        age: 18,
        address: {
            city: "北京",
        },
        hobby: ["台球", "篮球"],
        fn: function () {
            console.log(123);
        },
    };

    const obj2 = deepClone(obj1);
    obj2.age = 20;
    console.log(obj1);
    console.log(obj2);

    // function deepClone(obj) {
    //     return JSON.parse(JSON.stringify(obj1))
    // }

    function deepClone(obj) {
        if (typeof obj !== "object" || obj == null) {
            return obj;
        }
        let res = obj instanceof Array ? [] : {};
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                res[key] = deepClone(obj[key])
            }
        }

        return res;
    }

深克隆.png

3.何时使用==何时使用===

==隐式类型转换

100 == '100'

0 == ''

0 == false

false == ''

null == undefined

只有obj == null使用双等

if(obj === null || obj===undefined) {

}

演示代码

 console.log(100 == '100'); // true
 console.log(0==''); // true
 console.log(0==false); // true
 console.log(""==false); // true
 console.log(null==undefined); // true

 let obj = {age : 19};
 if(obj.age === 19) {
    console.log(1);
 }
 // 只有obj == null使用双等
 if(obj==null){

 }
 if(obj === null || obj===undefined) {

 }

4.哪些是truly变量?哪些是falsely变量?

什么是truly变量?什么是falsely

  • truly变量:!!val === true
  • falsely变量:!!val === false

除了falsely变量,都是truly变量

  • 数字0
  • NAN
  • 空字符串
  • null
  • undefined

演示代码

`// 数字0、NaN、空字符串、null、undefined是falsely变量
 console.log(!!"" === false); //true
 console.log(!!NaN === false); //true
 console.log(!!0 === false); //true
 console.log(!!null === false); //true
 console.log(!!undefined === false); //true`

5.原型和原型链

复习class基础语法

  • class
  • construct
  • extends
  • super
  • instanceof

什么是原型

原型.png

什么是原型链

原型链.png

演示代码

    class Person {
        constructor(name,age){
            this.name=name;
            this.age=age;
        }
        sayHi(){
            console.log(`${this.name}hi 我${this.age}岁`);
        }
    }
    // 子级继承
    class Student extends Person {
        constructor(name,age,sex){
            super(name,age);// 继承父级的name,age
            this.sex = sex
        }
        learn(){
            console.log(`我是${this.name}${this.age}${this.sex}`);
        }
    }
    // 实例化
    const x = new Student("张三",19,"男");
    x.sayHi();
    x.learn();
    // instanceof
    console.log(x instanceof Student);