javaScript-系统知识点【 常见问题及其解决办法】

会造成内存泄漏的情况(中级)

  • setTimeout的第⼀个参数使⽤字符串⽽非函数的话,会引发内存泄漏。
// setTimeout 的错误使用
setTimeout('666', 100)
// setTimeout 的正确用法
setTimeout( () => {
    console.log('666')
}, 1000)

前端常见内存泄漏及解决方案

如何捕获 JS 程序的异常?

两种方式

  • try catch
  • window.onerror
// 手动
try {
    // todo
} catch (ex) {
    console.log(ex) // 手动捕获 catch
} finally {
    // todo
}

// 自动捕获
window.onerror = function (message, source, lineNom, colNom, error) {
    // 第一, 对跨域的 js, 如 CDN 的, 不会有详细的报错信息
    // 第二, 对于压缩的 js, 还要配合 sourceMap 反查到未压缩代码的行、列
}

如何获取当前页面 url 参数

两种方式

  • 传统方式, 查找 location.search
  • 新 API, URLSearchParams
// 传统方式
function query(name) {
  // substr 从第一个之后开始截
  const search = location.search.substr(1); // 类似 array.slice(1)
  // search: 'a=10&b=20&c=30'
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, "i");
  const res = search.match(reg);
  if (res === null) {
    return null;
  }
  return res[2];
}
query("d");

// URLSeachParams 需高版本浏览器, 要做兼容性处理
function query(name) {
    const search = location.search;
    const p = new URLSearchParams(search);
    return p.get(name)
}
console.log(query("b"))

可以配合 Vue 路由传参进行学习

Vue3 通过 useRoute() 这个 hooks 函数获取

Vue2 通过 this.$route 获取

ES6的模块 与 CommonJS的模块 的异同

使用示例

/* E6模块使用 test.mjs */
export let name = '答案cp3'
 
// index.mjs
import { name } from './test.mjs'
/* commonjs 模块使用 */
//a.js
exports.action = function(){
    console.log('Action!');
}

//b.js
const a = require('./a.js')
a.action();

区别:

  1. ES6的模块是编译时加载,CommonJS是运行时加载
  2. ES6的模块是异步加载,CommonJS是同步加载
  3. ES6的模块是 引用,CommonJS 是对模块的浅拷贝

相同:

  1. ES6的模块 与 CommonJS的模块 都可以对引入的对象属性进行赋值

你可能感兴趣的:(2025,前端面经,javascript,开发语言,ecmascript,前端,面试)