魯斯前端布魯斯前端

文章中英模式

布魯斯前端JS面試題目 - 實作 JSON.stringify

學習如何手寫實作 JavaScript 的 JSON.stringify 方法,深入理解 JSON 序列化原理,提升前端面試競爭力。

影片縮圖

懶得看文章?那就來看影片吧

JSON.stringify 方法概述

JSON.stringify 是將 JavaScript 值或物件轉換為 JSON 字符串的標準方法。在前端開發中,這個方法經常用於資料傳輸、儲存和序列化。瞭解其內部運作機制不僅有助於更好地使用它,還能加深對 JavaScript 型別系統和遞迴算法的理解。

JSON.stringify 的特性

  • 1. 處理基本型別:字符串、數字、布林值、null 能直接轉換
  • 2. 處理複雜物件:物件和陣列會遞迴處理其屬性
  • 3. 忽略特殊值:undefined、函數、Symbol 在物件中會被忽略
  • 4. 處理循環引用:原生方法會拋出錯誤以避免無限遞迴
  • 5. 支援替換器:可使用函數或陣列自定義序列化過程
  • 6. 支援格式化:可指定縮排使輸出更易讀

在面試中,手寫實作 JSON.stringify 是考驗候選人對遞迴、型別處理和邊緣情況處理能力的好題目。

實作一個簡單版的 JSON.stringify

解答:實作一個僅支援基本功能的 JSON.stringify:

function basicJSONStringify(value) {
  // 处理 null
  if (value === null) {
    return 'null';
  }
  
  // 处理字符串
  if (typeof value === 'string') {
    return '"' + value.replace(/"/g, '\\"') + '"';
  }
  
  // 处理数字
  if (typeof value === 'number') {
    if (isNaN(value) || value === Infinity || value === -Infinity) {
      return 'null';
    }
    return String(value);
  }
  
  // 处理布尔值
  if (typeof value === 'boolean') {
    return String(value);
  }
  
  // 忽略 undefined、函数和 Symbol
  if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {
    return undefined;
  }
  
  // 处理数组
  if (Array.isArray(value)) {
    const items = value.map(item => 
      basicJSONStringify(item) === undefined ? 'null' : basicJSONStringify(item)
    );
    return '[' + items.join(',') + ']';
  }
  
  // 处理对象
  if (typeof value === 'object') {
    const props = [];
    for (const key in value) {
      if (Object.prototype.hasOwnProperty.call(value, key)) {
        const prop = basicJSONStringify(value[key]);
        if (prop !== undefined) {
          props.push('"' + key + '":' + prop);
        }
      }
    }
    return '{' + props.join(',') + '}';
  }
  
  return undefined;
}

// 测试范例
const obj = {
  name: "Bruce",
  age: 30,
  isAdmin: false,
  skills: ["JS", "React"],
  address: { city: "Taipei" }
};

console.log(basicJSONStringify(obj));