ES6的新特性和常見問題

整理關(guān)于ES6的問題,需要涵蓋ES6的主要新特性以及常見的問題。

首先,列出ES6的重要特性,然后針對(duì)每個(gè)特性給出可能的題和解析。

注意:問題要具有代表性,解析要簡潔清晰。

ES6 主要新特性

  1. let 和 const:塊級(jí)作用域變量聲明

  2. 箭頭函數(shù)() => {},簡化函數(shù)寫法,不綁定this

  3. 模板字符串:使用反引號(hào)`${}嵌入表達(dá)式

  4. 解構(gòu)賦值:從數(shù)組或?qū)ο笾刑崛≈?/p>

  5. 默認(rèn)參數(shù):函數(shù)參數(shù)默認(rèn)值

  6. Rest 參數(shù)...用于獲取函數(shù)的多余參數(shù)

  7. Spread 操作符...展開數(shù)組或?qū)ο?/p>

  8. 類(Class):基于原型的面向?qū)ο蟮恼Z法糖

  9. 模塊化importexport

  10. Promise:異步編程的解決方案

  11. 迭代器和生成器IteratorGenerator

  12. Set和Map:新的數(shù)據(jù)結(jié)構(gòu)

  13. Symbol:唯一且不可變的數(shù)據(jù)類型

  14. Proxy 和 Reflect:元編程

  15. 新的數(shù)組方法:如Array.from, Array.of, find, findIndex, includes

  16. 對(duì)象字面量增強(qiáng):屬性簡寫、方法簡寫、計(jì)算屬性名

  17. 函數(shù)參數(shù)尾逗號(hào):允許函數(shù)參數(shù)列表最后有逗號(hào)

高頻及解析

1. letconstvar 的區(qū)別?

  • var:函數(shù)作用域,存在變量提升(聲明提升,賦值不提升)

  • let:塊級(jí)作用域,不存在變量提升,存在暫時(shí)性死區(qū)(TDZ),不可重復(fù)聲明

  • const:塊級(jí)作用域,聲明時(shí)必須初始化,值不可修改(但對(duì)于對(duì)象,屬性可修改)


// 示例

console.log(a); // undefined(變量提升)

var a = 10;

console.log(b); // ReferenceError(暫時(shí)性死區(qū))

let b = 20;

2. 箭頭函數(shù)和普通函數(shù)的區(qū)別?

  • 語法:更簡潔

  • this:箭頭函數(shù)沒有自己的this,繼承外層作用域的this(定義時(shí)決定)

  • 不能作為構(gòu)造函數(shù):不能使用new

  • 沒有arguments對(duì)象:需用Rest參數(shù)代替

  • 沒有prototype屬性


const obj = {

name: 'Alice',

greet: function() {

setTimeout(() => {

console.log(this.name); // 'Alice'(箭頭函數(shù)繼承外層greet的this)

}, 100);

}

};

3. 解構(gòu)賦值的使用?


// 數(shù)組解構(gòu)

const [a, b] = [1, 2]; // a=1, b=2

// 對(duì)象解構(gòu)

const { name, age } = { name: 'Bob', age: 30 };

// 默認(rèn)值

const { color = 'red' } = {};

// 重命名

const { name: userName } = { name: 'Alice' };

4. Promise 是什么?有哪些狀態(tài)?

  • 定義:異步編程的解決方案,避免回調(diào)地獄

  • 狀態(tài)

  • pending:初始狀態(tài)

  • fulfilled:操作成功完成

  • rejected:操作失敗

  • 方法

  • then():處理成功狀態(tài)

  • catch():處理失敗狀態(tài)

  • finally():無論成功失敗都執(zhí)行

  • Promise.all():所有成功才成功

  • Promise.race():第一個(gè)完成的狀態(tài)決定結(jié)果


// 示例

const promise = new Promise((resolve, reject) => {

setTimeout(() => resolve('成功'), 1000);

});

promise

.then(res => console.log(res))

.catch(err => console.error(err));

5. SetMap 是什么?

  • Set:值唯一的集合

const set = new Set([1, 2, 2, 3]);

set.size; // 3

set.has(1); // true

  • Map:鍵值對(duì)集合,鍵可以是任意類型

const map = new Map();

map.set('name', 'Alice');

map.get('name'); // 'Alice'

6. 模板字符串的優(yōu)勢?

  • 支持多行字符串

  • 支持嵌入表達(dá)式

  • 標(biāo)簽?zāi)0澹ㄓ糜诤瘮?shù)調(diào)用)


const name = 'Alice';

const str = `Hello, ${name}!

How are you?`; // 多行

7. 類的繼承(extends)和 super 關(guān)鍵字?


class Animal {

constructor(name) {

this.name = name;

}

speak() {

console.log(`${this.name} makes a noise.`);

}

}

class Dog extends Animal {

constructor(name) {

super(name); // 調(diào)用父類構(gòu)造函數(shù)

}

speak() {

super.speak(); // 調(diào)用父類方法

console.log(`${this.name} barks.`);

}

}

8. async/await 是什么?(ES7,但常與ES6一起問)

  • 基于Promise的語法糖,使異步代碼像同步

  • async函數(shù)返回Promise

  • await后跟Promise,等待其解決


async function fetchData() {

try {

const res = await fetch('url');

const data = await res.json();

return data;

} catch (error) {

console.error(error);

}

}

9. 模塊化(import/export)?

  • 導(dǎo)出

// 命名導(dǎo)出

export const name = 'Alice';

export function hello() {};

// 默認(rèn)導(dǎo)出

export default class MyClass {};

  • 導(dǎo)入

import MyClass, { name, hello } from './module.js';

10. 什么是 Symbol?使用場景?

  • 唯一值,常用于避免屬性名沖突

const sym = Symbol('key');

const obj = {

[sym]: 'value' // 作為屬性名

};

11. Proxy 是什么?使用場景?

  • 創(chuàng)建對(duì)象的代理,攔截基本操作(如屬性查找、賦值等)

  • 使用場景:數(shù)據(jù)綁定、驗(yàn)證、日志等


const target = {};

const handler = {

get: function(obj, prop) {

return prop in obj ? obj[prop] : 37;

}

};

const p = new Proxy(target, handler);

p.a = 1;

console.log(p.a, p.b); // 1, 37


考點(diǎn)總結(jié)

  1. 作用域let/const 的塊級(jí)作用域

  2. 函數(shù):箭頭函數(shù)的特性(尤其是this

  3. 異步Promiseasync/await 的使用

  4. 面向?qū)ο?/strong>:Class 語法和繼承

  5. 數(shù)據(jù)結(jié)構(gòu)Set/Map 的使用場景

  6. 模塊化import/export 的語法

  7. 新API:數(shù)組和對(duì)象的新方法

掌握這些核心內(nèi)容,即可應(yīng)對(duì)大多數(shù) ES6 相關(guān)的問題!

ES6 (ECMAScript 2015) 核心特性及高頻問題解析

一、ES6 核心新特性

  1. let/const:塊級(jí)作用域變量聲明
  2. 箭頭函數(shù)() => {},無自己的this
  3. 模板字符串`Hello ${name}`
  4. 解構(gòu)賦值const {a, b} = obj
  5. 默認(rèn)參數(shù)function(a = 1) {}
  6. Rest/Spread...運(yùn)算符
  7. 類(Class):面向?qū)ο笳Z法糖
  8. 模塊化import/export
  9. Promise:異步解決方案
  10. 新數(shù)據(jù)結(jié)構(gòu):Set、Map、Symbol
  11. 迭代器/生成器Iterator/Generator
  12. 對(duì)象字面量增強(qiáng):屬性簡寫、計(jì)算屬性名
  13. 新數(shù)組方法find()、includes()

高頻問題及解析

1. let/const vs var 區(qū)別?

{
  var a = 1;
  let b = 2;
  const c = 3;
}
console.log(a); // 1 (函數(shù)作用域)
console.log(b); // ReferenceError (塊級(jí)作用域)
console.log(c); // ReferenceError
  • var:函數(shù)作用域,變量提升
  • let:塊級(jí)作用域,不可重復(fù)聲明
  • const:塊級(jí)作用域,聲明時(shí)必須賦值,值不可改(對(duì)象屬性可改)

2. 箭頭函數(shù)的特性?

const obj = {
  name: 'Alice',
  greet: () => console.log(this.name), // this指向window
  greet2: function() {
    setTimeout(() => console.log(this.name), 100) // this繼承外層
  }
};
obj.greet(); // undefined
obj.greet2(); // 'Alice' (1秒后)
  • 無自己的this/arguments/super
  • 不能作為構(gòu)造函數(shù)(不可new
  • prototype屬性

3. Promise 工作原理及方法?

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Success'), 1000);
});

p.then(res => console.log(res))
 .catch(err => console.error(err))
 .finally(() => console.log('Done'));

// 組合方法
Promise.all([p1, p2]) // 全部成功
Promise.race([p1, p2]) // 第一個(gè)完成
Promise.any([p1, p2]) // 第一個(gè)成功 (ES2021)

4. 解構(gòu)賦值的應(yīng)用場景?

// 數(shù)組解構(gòu)
const [first, , third] = [1, 2, 3]; 

// 對(duì)象解構(gòu)
const { name, age = 18 } = user; 

// 函數(shù)參數(shù)
function f({ id, type = 'text' }) {} 

// 交換變量
[a, b] = [b, a]; 

5. Class 繼承實(shí)現(xiàn)?

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(`${this.name} makes a noise`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 必須調(diào)用super
    this.breed = breed;
  }
  
  speak() {
    super.speak(); // 調(diào)用父類方法
    console.log('Woof!');
  }
}

6. Set/Map 使用場景?

// Set:值唯一性
const unique = new Set([1, 2, 2, 3]); // {1, 2, 3}
unique.has(2); // true

// Map:鍵值對(duì)集合(鍵可為任意類型)
const map = new Map();
map.set({}, 'value');
map.get(key); 

7. 模塊化導(dǎo)出/導(dǎo)入方式?

// 導(dǎo)出方式
export const name = 'ES6';
export default function() {};
export { name as myName };

// 導(dǎo)入方式
import myFunc, { name, myName } from './module';
import * as module from './module';

8. 生成器(Generator)工作原理?

function* idGenerator() {
  let id = 0;
  while(true) {
    yield id++;
  }
}

const gen = idGenerator();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1

9. Proxy 的應(yīng)用場景?

const target = {};
const handler = {
  get: (obj, prop) => {
    console.log(`訪問屬性: ${prop}`);
    return prop in obj ? obj[prop] : 37;
  },
  set: (obj, prop, value) => {
    console.log(`設(shè)置屬性: ${prop}=${value}`);
    obj[prop] = value;
    return true; // 表示成功
  }
};

const proxy = new Proxy(target, handler);
proxy.age = 18; // 日志: 設(shè)置屬性: age=18
console.log(proxy.name); // 日志: 訪問屬性: name → 37

10. ES6 數(shù)組新增方法?

// 查找
[1, 2, 3].find(x => x > 1); // 2
[1, 2, 3].findIndex(x => x === 2); // 1

// 包含檢查
['a', 'b'].includes('b'); // true

// 轉(zhuǎn)換
Array.from('123'); // [1, 2, 3]
Array.of(1, 2, 3); // [1, 2, 3]

// 填充
new Array(3).fill(7); // [7, 7, 7]

核心考點(diǎn)總結(jié)

  1. 作用域管理let/const的塊級(jí)作用域
  2. 函數(shù)特性:箭頭函數(shù)的this綁定規(guī)則
  3. 異步編程:Promise鏈?zhǔn)秸{(diào)用/錯(cuò)誤處理
  4. 面向?qū)ο?/strong>:Class繼承與super關(guān)鍵字
  5. 數(shù)據(jù)結(jié)構(gòu):Set去重/Map鍵值存儲(chǔ)
  6. 模塊化:ES Module的導(dǎo)入導(dǎo)出規(guī)則
  7. 元編程:Proxy攔截器應(yīng)用
  8. 數(shù)據(jù)處理:解構(gòu)賦值/Rest-Spread運(yùn)算符

掌握這些核心特性,能解決90%的ES6相關(guān)問題。實(shí)際編碼中推薦結(jié)合Babel使用,確保瀏覽器兼容性。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容