Skip to content

JavaScript 核心

一、变量与数据类型

js
// 声明(推荐优先用 const,需要修改再用 let)
const name = '小明'
let count = 0
count = 1

// 常见类型
const str = 'hello'          // 字符串
const num = 42               // 数字
const isOk = true            // 布尔
const arr = [1, 2, 3]        // 数组
const obj = { id: 1, name: '手机' }  // 对象

二、ES6+ 高频语法(务必熟练)

解构赋值

js
const product = { id: 1, name: '手机', price: 3999 }
const { id, name } = product      // 从对象里取值

const [first, second] = [10, 20]  // 从数组里取值

箭头函数

js
const double = (x) => x * 2
const sum = (a, b) => {
  return a + b
}

模板字符串

js
const price = 3999
const text = `当前价格:¥${price}`   // 推荐,代替字符串拼接

展开运算符

js
const base = { id: 1 }
const full = { ...base, name: '手机' }   // 复制并追加属性,不可变更新
const nums = [1, 2]
const more = [...nums, 3]

数组方法(后端返回列表后最常用)

js
const products = [
  { id: 1, name: '手机', price: 3999, stock: 10 },
  { id: 2, name: '耳机', price: 299, stock: 0 },
]

const cheap = products.filter(p => p.price < 500)   // 过滤
const names = products.map(p => p.name)             // 映射
const total = products.reduce((acc, p) => acc + p.price, 0) // 聚合
const found = products.find(p => p.id === 2)        // 查找
const hasStock = products.some(p => p.stock > 0)    // 任一满足

三、异步编程:从回调到 async/await

接口请求是异步的——发起请求后不能立即拿到结果。现代写法用 async/await

js
async function fetchProducts() {
  const res = await fetch('/api/product/list?page=1')
  const data = await res.json()
  return data
}

async/await 的底层是 Promise:

js
fetch('/api/product/list')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error('请求失败', err))

为什么用 async/await

回调地狱层层嵌套难以阅读。async/await 让异步代码看起来像同步代码,是现在的标准写法。抓包时发现接口返回的不是期望数据,先检查 await 是否漏写。

四、DOM 操作与事件

框架(Vue/React)会自动处理 DOM,但理解原理很重要:

js
const btn = document.querySelector('#add-btn')
btn.addEventListener('click', () => {
  const count = document.querySelector('#count')
  count.textContent = Number(count.textContent) + 1
})

框架时代还需要学 DOM 吗

需要懂原理,但日常开发不直接操作。框架采用"数据驱动视图":改数据,页面自动更新。这是第 4/5 部分最核心的思想,提前在心里种下。

五、闭包与作用域(面试高频)

js
function createCounter() {
  let count = 0            // count 被闭包捕获
  return function () {
    count++
    return count
  }
}
const counter = createCounter()
counter() // 1
counter() // 2   // count 一直被记住

一句话:闭包就是"函数 + 它记住的外部变量"。React 的 Hooks、Vue 的响应式内部都依赖类似机制。

六、模块化

js
// utils.js
export const formatPrice = (price) => `¥${price.toFixed(2)}`
export const defaultPageSize = 10

// main.js
import { formatPrice, defaultPageSize } from './utils'

大型项目还会用到 export default(默认导出,导入时可任意命名)。

本章自测

能写出:filter/map/reduce 的用法、async/await 请求接口、解构 + 展开更新对象。这三组能力覆盖商城前端 80% 的代码场景。

基于 MIT 协议发布,可自由学习与修改