数组和对象的扁平化

数组和对象的扁平化是将多层嵌套的数组或对象转换为只有一层的形式。

  1. 使用递归和 concat 方法实现扁平化数组:

    1
    2
    3
    4
    5
    6
    7
    8
    function flattenArrayRecursive(arr) {
    //[1,2,3,[4,5,6]]=>[1,2,3,4,5,6]
    return Array.isArray(arr)
    ? arr.reduce((acc, curr) => {
    return acc.concat(flattenArrayRecursive(curr));
    }, [])
    : [arr];
    }
  2. 使用扩展运算符和递归方法扁平化数组:

    1
    2
    3
    4
    5
    function flattenArraySpread(arr) {
    return arr.some(Array.isArray)
    ? flattenArraySpread([].concat(...arr))
    : arr;
    }
  3. 使用 reduce 方法和 Object.assign 扁平化对象:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function  flattenObjectReduce(obj,prefix=''){
    return Object.keys(obj).reduce((acc,key)=>{
    var pre=prefix.length?prefix+'.':'';
    if(typeof obj[key]==='object'&&obj[key]!==null){
    Object.assign(acc,flattenObjectReduce(obj[key],pre+key))
    }else{
    acc[pre+key]=obj[key]
    }
    return acc;
    },{})
    }

Object.create

Object.create()是 js 中的一个方法,用于创建一个新对象,新对象的原型(prototype)是指定的对象。

1
2
3
4
5
function create(obj) {
function F() {}
F.prototype = obj;
return new F();
}

instanceof 方法

instanceof 用于判断构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。

  • 实现步骤:
    • 获取类型的原型
    • 获得对象的原型
    • 一直循环判断对象的原型是否等于类型的原型,直到对象原型为 null,因为原型链最终为 null
1
2
3
4
5
6
7
8
9
10
11
12
13
function myInstanceof(obj, fn) {
let proto = Object.getPrototypeOf(obj); //获取对象的原型
let prototype = fn.prototype; //获取构造函数的prototype对象
while (true) {
if (!proto) {
return false;
}
if (proto == prototype) {
return true;
}
proto = Object.getPrototypeof(prop);
}
}

手写 new 操作符

  • 首先创建一个空对象

  • 设置原型,将对象的原型设置为函数的 prototype 对象

  • 让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)

  • 判断函数的返回值类型,如果是值类型,返回创建的对象,如果是引用类型,就返回这个引用类型的对象。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    function objectFactory() {
    let newObject = null;
    let constructor = Array.prototype.shift.call(arguments);
    let result = null;
    // 判断参数是否是一个函数
    if (typeof constructor !== "function") {
    console.error("type error");
    return;
    }
    // 新建一个空对象,对象的原型为构造函数的 prototype 对象
    newObject = Object.create(constructor.prototype);
    // 将 this 指向新建对象,并执行函数
    result = constructor.apply(newObject, arguments);
    // 判断返回对象
    let flag =
    result && (typeof result === "object" || typeof result === "function");
    // 判断返回结果
    return flag ? result : newObject;
    }
    // 使用方法
    objectFactory(构造函数, 初始化参数);