js文档MDN doc

简介

JavaScript 是一种属于网络的脚本语言,已经被广泛用于 Web 应用开发,常用来为网页添加各式各样的动态功能,为用户提供更流畅美观的浏览体验。本节主要带大家熟悉 JavaScript 语句,巩固 JavaScript 基础,应对相关面试提问。

程序的三种基本结构

  • 顺序结构:从上到下执行的代码就是顺序结构,程序默认就是由上到下顺序执行的;
  • 分支结构:根据不同的情况及判断,执行对应代码;
  • 循环结构:重复执行一段代码。

JS 组成

JS 由三部分组成,分别是:

  • DOM(文档对象模型)
  • BOM(浏览器对象模型)
  • ES(ECMAScript 规范,如 ES5、ES6 等)

前端框架与工具

类库:

  • JQuery
  • Lodash

JS 框架:

  • React
  • Vue
  • Angular
  • Ext JS
  • Backbone

工具:

  • webpack(Build)
  • jest(Test)
  • ESlint(Lint)
  • Template(EJS)
  • 应用方面的(Echarts/D3/three)

区别:

框架—包含—>库
框架—调用—>运行代码(如:生命周期函数)—调用—>库


数据类型及类型判断

JavaScript 的基本数据类型有:undefinednullbooleannumberstringsymbol(ES6)、bigint(ES2020),引用类型有:object(包括数组、函数、对象等)。

常见类型判断方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// undefined(未定义)
typeof undefined // "undefined"

// 字符串
typeof "" // "string"

// 布尔值
typeof true // "boolean"

// number
typeof 0 // "number"
isNaN(+"a") // true

// function
typeof Function; // "function"

// object(Array 和 null 也是 object 类型,所以不能用 typeof 判断类型了)
Object.prototype.toString.call([]) // "[object Array]"
Array.isArray([]) // true
[] instanceof Array // true
Object.prototype.toString.call({}) // "[object Object]"
({}) instanceof Object // true
Object.prototype.toString.call(null) // "[object Null]"
Function('console.log(Object.prototype.toString.call(arguments))')() // "[object Arguments]"

// 判断对象是否为普通对象
var v={};v!==undefined&&v!==null&&(v).constructor==={}.constructor // true

类型判断方法总结

  • typeof:可判断基本类型,不能区分 null、数组、对象。
  • instanceof:判断对象实例与构造函数的关系,不能判断基本类型。
  • Object.prototype.toString.call():最准确,推荐使用。

常用内置对象

  • Object:所有对象的父类型。
  • Array:数组对象。
  • Function:函数对象。
  • Date:日期对象。
  • RegExp:正则表达式对象。
  • Math:数学对象,提供数学常数和函数。
  • JSON:用于解析和序列化 JSON 数据。

常见面试题

1. ===== 的区别

  • ==:先进行类型转换再比较,称为“宽松等于”。
  • ===:不进行类型转换,类型和值都相等才为 true,称为“严格等于”。

2. 如何判断数组

1
2
3
Array.isArray(arr); // 推荐
Object.prototype.toString.call(arr) === '[object Array]'
arr instanceof Array

3. 如何实现深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 简单方式(有局限性)
const copy = JSON.parse(JSON.stringify(obj));

// 递归实现
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(deepClone);
const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}

4. 闭包的作用

  • 保护变量不被外部访问(数据私有化)
  • 保持变量的持久性

5. 事件委托

通过事件冒泡,将事件绑定到父元素上,利用事件对象的 target 属性判断事件源。


其他常用知识点

  • 作用域与作用域链
  • 原型与原型链
  • this 指向
  • 异步编程(Promise、async/await)
  • ES6 新特性(let/const、箭头函数、解构赋值、模板字符串、扩展运算符等)

更多内容请参考 MDN JavaScript 指南