js基础常考面试题

变量类型和计算

  1. typeof能判断哪些类型
  2. 何时使用===何时使用==
  3. 值类型和引用类型的区别
  4. 手写深拷贝
知识点
  1. 值类型vs引用类型
  2. typeof运算符
  3. 深拷贝
值类型和引用类型

一般来说,值类型的变量值存储在栈内存中,引用类型存储在堆内存中;对于变量来说,引用类型的变量存储的是内存地址。可以这么理解:值类型所占的内存都很少,所以直接存的值,而引用类型可能非常大,计算机查找起来耗时,所以存储的是内存地址,而真正的值存在内存中某一地址块内。

常见值类型

常见值类型symbol、undefined、string、number、boolean、bigint,常见引用类型object(null指向的是空地址)、function(特殊的引用类型)

typeof运算符

typeof运算符能识别所有值类型、函数,判断是否是引用类型(不可再细分)

深拷贝
var obj = {
    age: 20,
    name: 'ainuo5213',
    address: {
        city: '北京',
    },
    arr: ['a', 'b', { thumble: ['a', 'b'] }]
};

function clone(source, isDeepClone) {
    isDeepClone = isDeepClone || true;
    if(typeof source !== 'object' || source == null) {
        return source
    }
    var target = isObject(source) ? {} : [];
    if (isDeepClone) {
        for (var key in source) {
            var _tempSource = source[key];
            if (source.hasOwnProperty(key)) {
                if (typeof _tempSource !== 'object' || _tempSource == null) {
                    target[key] = _tempSource;
                } else if (isArray(_tempSource)) {
                    target[key] = clone(_tempSource, true);
                } else if (isObject(_tempSource)) {
                    target[key] = clone(_tempSource, true);
                }
            }
        }
        return target
    } else {
        return target
    }
}

function isObject(obj){
    return Object.prototype.toString.call(obj) === '[object Object]';
}

function isArray(arr) {
    return Object.prototype.toString.call(arr) === '[object Array]';
}

var clonedObj = clone(obj);
obj.name = 'ainuo5214';
console.log(clonedObj); // ainuo5213
类型转换
  • 显示类型转换
    显示类型转换即通过特定方法进行的转换,如Number()、String()、toString()等。
  • 隐式类型转换
    隐式类型转换即不使用显示类型转换的方式进行变量类型转换,如四则运算符、逻辑判断等

==运算符适用于判断对象中某个属性是否存在,如: obj.xx == null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值