Is it possible to determine if an object created with Object.create inherits from Array in JavaScript?

后端 未结 5 1931
野的像风
野的像风 2021-01-12 12:59

Identifying which objects are which is complicated in JavaScript, and figuring out which objects are arrays has something of a hacky solution. Fortunately, it manages to wor

5条回答
  •  隐瞒了意图╮
    2021-01-12 13:14

    ECMAScript 5 has introduced Array.isArray() into javascript which provides a reliable way to check. For older browsers, we fix that by (quoted from this book)

    function isArray(value) {
        if (typeof Array.isArray === "function") {
             return Array.isArray(value);
        } else {
             return Object.prototype.toString.call(value) === "[object Array]";
        }
    }
    

    But i just found out the built-in function Array.isArray does not work correctly when we use Object.create (tested in chrome). I came up with a method that works:

    function isArray(value) {
         if (typeof value === "undefined" || value === null) {
              return false;
         }
         do {
              if (Object.prototype.toString.call(value) === "[object Array]") {
                   return true;
              }
              value= Object.getPrototypeOf(value);
         } while (value);
    
         return false;
    }
    

    Use it:

    var arr = Object.create(Array.prototype);
    var arr1 = Object.create(Object.create(Array.prototype));
    var arr2 = new Array();
    var arr3 = [];
    isArray(arr); 
    isArray(arr1); 
    isArray(arr2); 
    isArray(arr3); 
    

提交回复
热议问题