js进阶

一.箭头函数(()=> {})

  • 优势:简化语法,继承外层this指向(解决回调地狱的this问题)

  • 特性:无this绑定(this指向定义时的外层作用域,而非调用时),无arguments对象(需用···替代),单参数可省略括号,单语句可省略{}和return。

const arr = [1,2,3]
const newARR = arr.map(item => item * 2);//[2,4,6]

解决this 问题
const user = {
  name:"小红"
  saiHi:function() {
    /* setimeout(()=>{
      console.log(`Hi,${this.name}`)//正确:this继承外层sayHi的this
   },1000)*/
      setTimeout(function() {
      // 这里的回调函数是被 window 调用的 → this 指向 window
      console.log("回调 this:", this.name); // window 没有 name 属性 → 输出 undefined(或报错)
    }, 1000); 
  }//传统函数,谁调用指向谁,setimeout()是被全局对象调用的,this指向window
}
uesr.sayHi()//输出"Hi,小红"

二.模板字符串(`字符串${变量}`)

优势:替代字符串拼接,支持换行,变量嵌入

const name = '小李';
const age = 20;
//变量嵌入
const info = `姓名:${name},年龄:${age};//"姓名:小李,年龄:20"
const html = `
  <div class="users">
     <p>${name}</p>
  </div>
`;

三.解构赋值

1.数组结构

//1.按顺序提取元素
const arr = [10,20,30]
const [a,b,c] = arr;
console.log(a,b,c)//10 20 30;con

//2.跳过不需要函数
const arr = [10,20,30,40,50];
const [a, , , d] = arr
console/log(a.d)//10 40;

//3.提取剩余元素(...),剩余元素不可以在中间
const arr = [10,20,30,40,50];
const [a,...rest] = arr;
console.log(a);//10
console.log(rest);//[20,30,40,50]

// 错误写法:剩余元素不能在中间
// const [a, ...rest, b] = arr; // SyntaxError

//4.设置默认值
const arr = [10,undefined,30];
const [a,b=200,c,d=400] = arr;
console.log(a,b,c,d); //10 200 30 400

// 数组长度不足的情况(只定义了 2 个元素,提取 3 个)
const [x, y, z = 300] = [100, 200];
console.log(x, y, z); // 100 200 300

//5.结构嵌套
const arr = [10,[20,30],40];
const [a,[,b],c] = arr;
console.log(a,b,c);10 30 40

2.对象解构

//1.按属性名提取

const user = {name:"小明",age:18,city:"北京"};

const {name,age} = user;
console.log(name,age);//小明 18

//2.给提取的变量重命名
const user = { name: "小红", age: 20, userCity: "上海" };
// 提取 userCity 属性,并重命名为 city
const { name, userCity: city } = user;
console.log(name, city); // 小红 上海(变量名是 city,不是 userCity)

//3.设置默认值,当对象中没有对应属性,或属性值为 undefined 时,使用默认值(避免变量为 undefined)
const user = { name: "小李", age: undefined };
// 给 age 设置默认值 18,给 gender 设置默认值 "男"(对象中无 gender 属性)
const { name, age = 18, gender = "男" } = user;
console.log(name, age, gender); // 小李 18 男

//4.剩余属性:提取剩余所有属性(...)
const user = { name: "小王", age: 22, city: "广州", job: "前端" };
// 提取 name 和 age,剩余属性存入 rest 对象
const { name, age, ...rest } = user;
console.log(name, age); // 小王 22
console.log(rest); // { city: "广州", job: "前端" }(新对象)

//5.解构嵌套
const user = {
  name:"小张";
  age:25;
  address: {
    province: "广东省",
    city: "深圳",
    detail: "XX街道XX小区"
  }
};
// 提取外层 name,深层 address 中的 city 和 detail
const {name,address:{city,detail}} = user
console.log(name,city,detail);//小张 深圳 XX街道XX小区

// 进阶:给嵌套属性重命名+设默认值
const { address: { province = "未知省份" } } = user;
console.log(province); // 广东省(对象中有该属性,默认值不生效

//6.混合
const addressList = [
  { id: 1, contact: "小明", phone: "13800138000" },
  { id: 2, contact: "小红", phone: "13900139000" }
];

// 提取数组第 0 个元素的 contact 和 phone
const [{ contact, phone }] = addressList;
console.log(contact, phone); // 小明 13800138000

// 提取数组第 1 个元素,并给 contact 重命名为 name
const [, { contact: name, phone: tel }] = addressList;
console.log(name, tel); // 小红 13900139000

四.扩展运算符(...)

实用场景:数组合并,对象复制(浅拷贝),函数不定参

//数组合并
const arr1 = [1,2];
const arr2 = [3,4];
const mergedArr = [...arr1,...arr2];//[1,2,3,4]

//浅拷贝
const user = {name:"小王"};
const newUser = {...user,age:25};//{name:"小王",age:25}

// 函数不定参(替代 arguments)
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6

五.promise解决回调地狱

关键方法:Promise.resolve(),Promise.reject(),then(),catch(),finally().

//封装异步请求(模拟接口)
function fetchData(){
   return new Promise((resolve ,reject) => {
    setTimeout(()=>{
      const success = true;
      if(success) {
         resolve({name:"小刘"});
      } else {
           reject("请求失败");
      }
     },1000);
   })
}

//调用异步函数
fetchData()
  .then(data => console.log("成功:",data))
  .catch(err => console.log("失败:",err)
  .finally(() => console.log("请求结束(无论成功失败"));

六.类(class)

  • 核心优势:简化原型链继承,使面向对象编程更直观

  • 关键特性:constructor(构造函数)、extends(继承)、super(调用父类方法)

七.模块系统(import/export)

  • 核心优势:实现代码模块化(拆分文件、复用代码、避免全局污染)

  • 分类:默认导出(export default)、命名导出(export const

//模块文件:uesr.js
export const name = "小赵";//命名导出
export function sayHIi() {
  console.log("Hello");
}

export default class User {
   constructor(age){//默认导出
    this.age = age;
   }
}//唯一标识,引入可不用{}

//引入模块:index.js
import User,{name,sayHi} from "./user.js";
console.log();//"小赵"
sayHi();//Hello

八.实用方法

1.Array.prototype.includes() 作用:判断数组是否包含某个元素

2.指数运算符(**)

3.Object.values() 获得对象的值数组

4.Object.entires() 获得键值对数组

const user = {name:"小钱",age:24}
Object.values(user);//["小钱","24"]
object.entries(user);//[["name","小钱"],["age",24]]
for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}

5.Array.prototype.flat()/flatMap() 作用:数组扁平化

//flat(depth):depth为扁平化深度,默认1
const arr = [1,[2,[3]]]];
arr.flat();//[1,2,[3]]
arr.flat(2);//[1,2,3]

//flatMap():先map 再flat
const arr2 = [1,2];
arr2.flatMap(item=>[item,item*2]);[1,2,2,4]

6.String.prototype.trimStart()/trimEnd() 去除字符串开头/结尾的空白

7.Object.fromEntries() 将键值对数组转为对象

8.BigInt()处理超大整数

九.async/await

  • 核心优势:使异步代码 “看起来像同步”,彻底解决回调地狱

  • 关键特性:async 声明异步函数,await 等待 Promise 完成

// 结合之前的 fetchData 函数
async function getUserData() {
  try {
    const data = await fetchData(); // 等待异步结果,代码暂停但不阻塞线程
    console.log("成功:", data);
    return data;
  } catch (err) {
    console.error("失败:", err);
  }
}
getUserData();

十.异步迭代器(for await...of)

//异步生成器函数
async function* asncGenertor(){
  yield Promise.resolve(1);
  yield Promise.resolve(2);
}

//
async function test(){
 for await (const num of asncGenertor()){
    console.log(num);
}
}

test();

十一.

正向断言(?<=条件)匹配条件后面内容

反向断言(<!条件)匹配 “不是条件后面” 的内容

正则对象.exec(待匹配字符串)

const reg2 = /(?<=¥)\d+/;
reg2.exec("价格:¥99"); // ["99"]


js进阶
http://localhost:8090//archives/jsjin-jie
作者
王雅慧
发布于
2025年11月12日
许可协议