js内置对象

114 阅读2分钟

一、核心内置对象分类

JavaScript 内置对象可分为以下几大类(面试常考):

1. 全局对象

  • window(浏览器环境)/globalThis(通用)
  • 全局函数:parseInt()decodeURI()isNaN()

2. 基本数据类型包装对象

  • StringNumberBooleanSymbol

3. 集合对象

  • ArraySetMapWeakSetWeakMap

4. 工具对象

  • ObjectFunctionDateMathJSON

5. 错误对象

  • ErrorTypeErrorSyntaxError

二、问题

1. 基本包装类型 vs 原始值

  • 问题new String('hi')'hi' 的区别?
    • 'hi' 是原始值(Primitive),无方法。
    • new String('hi') 是对象,有方法(如 .length)。
    • 关键点:原始值调用方法时,JS 会自动创建临时包装对象(如 'hi'.toUpperCase())。

2. Array 常用方法

分类方法
增删push()pop()shift()unshift()splice()slice()
排序sort()reverse()
合并concat()flat()flatMap()
迭代forEach()map()filter()reduce()some()every()
查找find()findIndex()includes()indexOf()

3. Map vs Object 的选择

特性ObjectMap
键类型字符串或 Symbol任意类型(对象、函数等)
顺序不保证(ES2015+ 按插入顺序)严格按插入顺序
大小需手动计算(Object.keys直接通过 size 获取
性能适合少量键值对适合大量增删操作

4. Set 的应用场景

  • 去重[...new Set([1, 2, 2])][1, 2]
  • 交集/并集/差集
    const a = new Set([1, 2]);  
    const b = new Set([2, 3]);  
    const intersection = new Set([...a].filter(x => b.has(x))); // {2}  
    

5. Date 对象的时区问题

  • 问题:如何获取 UTC 时间?
    const now = new Date();  
    now.getUTCFullYear(); // UTC 年份  
    now.toISOString();    // "2025-06-29T12:00:00.000Z"(UTC 格式)  
    

6. Math 对象常用方法

  • 随机数Math.random()(返回 [0, 1) 之间的数)
  • 取整Math.floor()Math.ceil()Math.round()
  • 最大值/最小值Math.max(1, 2, 3)Math.min(...[1, 2, 3])

三、原型链与内置对象

  • 问题Array.prototype 上有哪些方法?
    :常见方法如 map()filter()push() 等都定义在 Array.prototype 上。

    • 验证
      console.log(Array.prototype.hasOwnProperty('map')); // true  
      
  • 问题:如何自定义数组方法?
    :通过扩展原型链(不推荐直接修改,可能导致冲突):

    Array.prototype.myMethod = function() {  
      return this.map(x => x * 2);  
    };  
    [1, 2].myMethod(); // [2, 4]  
    

四、错误处理与内置错误类型

错误类型触发场景
SyntaxError语法错误(如 if (a = 1)
TypeError类型错误(如 undefined.foo()
ReferenceError引用不存在的变量(如 console.log(abc)
RangeError范围错误(如 new Array(-1)
  • 自定义错误
    class MyError extends Error {  
      constructor(message) {  
        super(message);  
        this.name = 'MyError';  
      }  
    }  
    throw new MyError('自定义错误');  
    

五、高频代码题

  1. 数组去重

    const arr = [1, 2, 2, 3];  
    const unique = [...new Set(arr)]; // 方法1:使用 Set  
    const unique2 = arr.filter((v, i) => arr.indexOf(v) === i); // 方法2:使用 filter  
    
  2. 对象深拷贝

    function deepClone(obj) {  
      if (obj === null || typeof obj !== 'object') return obj;  
      const clone = Array.isArray(obj) ? [] : {};  
      for (const key in obj) {  
        clone[key] = deepClone(obj[key]);  
      }  
      return clone;  
    }  
    
  3. 函数柯里化

    function add(a, b) {  
      return a + b;  
    }  
    const curriedAdd = a => b => a + b;  
    curriedAdd(3)(5); // 8