代码之家  ›  专栏  ›  技术社区  ›  Fuzzyma

如何检查数组是否为普通内置数组?

  •  1
  • Fuzzyma  · 技术社区  · 7 年前

    我尝试的是:

    arr instanceof Array // true for child classes, too
    Array.isArray(arr)   // same
    

    还有别的办法吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   T.J. Crowder    7 年前

    if (arr.constructor === Array) {
        // Yes, it is
    }
    

    但是 arr 领域 (例如子窗口或父窗口),该检查将为false,因为 arr.constructor 将参考 Array === 中的构造函数 你的

    如果你需要它是一个普通的数组 可能来自另一个领域,您可能想复制它:

    arr = Array.from(arr);
    

    我想到的另一个选择是:

    function isReallyAPlainArray(arr) {
        const getProto = Object.getPrototypeOf;
        try {
            // A plain array's prototype is Array.prototype, whose prototype is
            // Object. prototype, whose prototype is null
            return Array.isArray(arr) && getProto(getProto(getProto(arr))) === null;
        } catch (e) {
            // Prototype chain was too short; not a plain array
            return false;
        }
    }
    
    
    class MyArray extends Array { }
    
    console.log(isReallyAPlainArray([]));          // true
    console.log(isReallyAPlainArray(new MyArray)); // false

    这是因为普通数组的原型是 Array.prototype Object.prototype ,其原型是 null 阿里尔 如果是一个子类的实例,那里面会有另一层。这是跨领域的。它可以 也 被试图误导你的人打败 Object.setPrototypeOf ),但是。。。