小知识和一些面试题

56 阅读3分钟

此文记录一些零散小知识和一些我觉得不错的面试题,以备将来面试复习,尽量每天更一点

1.装箱

装箱的工作原理:当你访问基本类型的属性或方法时,JavaScript 会自动将基本类型装箱为其对应的对象类型。这个临时的对象允许你访问属性和方法,但它是短暂的,一旦属性或方法访问完成,这个对象就会被销毁。

需要注意的是,null 和 undefined 没有对应的对象类型,不能被装箱。所以访问它们的属性或方法会直接报错!所以时刻警惕 null 和 undefined 这俩坑。

2.动态导入模块

在某个特定时期导入引用模块,一直没在项目中用过,写点代码记录一下

const loadModule = async () => {  
  try {  
    const module = await import('./dynamicModule.js');  
    module.doSomething();  
  } catch (error) {  
    console.error('Failed to load module:', error);  
  }  
}

3.解构赋值别名,默认值

const test = {a:1,b:2}
const {a:c} = test//别名
const {c=5} = test//默认值

4.节流防抖

节流:节流是一种限制函数执行频率的技术。它的原理是,当事件被频繁触发时,函数会按照一定的时间间隔执行,而不是每次触发事件都执行。换句话说,在一个时间段内,只会执行一次事件处理函数。

function throttled1(fn, delay = 500) {
    let oldtime = Date.now()
    return function (...args) {
        let newtime = Date.now()
        if (newtime - oldtime >= delay) {
            fn.apply(null, args)//注意this指向
            oldtime = Date.now()
        }
    }
}

防抖:防抖是一种延迟执行的技术。它的原理是,当事件被触发时,延迟执行事件处理函数,并且在延迟时间内如果事件再次被触发,则重新开始计时。只有当事件在指定的时间内没有再次触发,事件处理函数才会执行。这样可以避免某些高频率的操作被频繁触发,从而提高性能。

let timer = null
function debounce(fn,delay){
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
        fn()
    },delay)
}

5. structuredClone

Window 接口的 structuredClone()  方法使用结构化克隆算法将给定的值进行深拷贝

const mushrooms1 = {
  amanita: ["muscaria", "virosa"],
};

const mushrooms2 = structuredClone(mushrooms1);

mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();

console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]

文章链接:MDN思否

6. in和hasOwnProperty

in 操作符会检查属性是否在对象及其[[Prototype]]原型链中。 hasOwnProperty(..) 只会检查属性是否在myObject 对象中,不会检查[[Prototype]] 链

7. 函数对象的length属性是其声明的参数的个数

const fn = (a,b)=>a+b
console.log(fn.length) // 2

8.undefined和undeclared

作用域中声明但还没有赋值的变量,是undefined的。相反,还没有在作用域中声明 过的变量,是undeclared的

image.png

9. 如何判断0.1+0.2 = 0.3

image.png

10. Object.prototype.toString.call() 判断值类型

console.log(Object.prototype.toString.call("jerry"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]

function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]

11.原生函数可以被当作构造函数来使用,但其构造出来的是对象而不是值

image.png

image.png