zoukankan      html  css  js  c++  java
  • JS判断是否是数组

      1、通过instanceof判断

    instanceof运算符用于检验构造函数的prototype属性是否出现在对象的原型链中的任何位置,返回一个布尔值。

    let a = [];
    a instanceof Array; //true
    let b = {};
    b instanceof Array; //false

    在上方代码中,instanceof运算符检测Array.prototype属性是否存在于变量a的原型链上,显然a是一个数组,拥有Array.prototype属性,所以为true。

    需要注意的是,prototype属性是可以修改的,所以并不是最初判断为true就一定永远为真。

    其次,当我们的脚本拥有多个全局环境,例如html中拥有多个iframe对象,instanceof的验证结果可能不会符合预期,例如:

    //为body创建并添加一个iframe对象
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);
    //取得iframe对象的构造数组方法
    xArray = window.frames[0].Array;
    //通过构造函数获取一个实例
    var arr = new xArray(1,2,3); 
    arr instanceof Array;//false

    导致这种问题是因为iframe会产生新的全局环境,它也会拥有自己的Array.prototype属性,让不同环境下的属性相同很明显是不安全的做法,所以Array.prototype !== window.frames[0].Array.prototype,想要arr instanceof Array为true,你得保证arr是由原始Array构造函数创建时才可行。

      2、通过constructor判断

    我们知道,实例的构造函数属性constructor指向构造函数,那么通过constructor属性也可以判断是否为一个数组。

    let a = [1,3,4];
    a.constructor === Array;//true

    同样,这种判断也会存在多个全局环境的问题,导致的问题与instanceof相同。

      3、通过Object.prototype.toString.call()判断

    Object.prototype.toString().call()可以获取到对象的不同类型,多个全局环境也适用

    // 检验是否是数组
      let a = [1,2,3]
      Object.prototype.toString.call(a) === '[object Array]';//true
      //检验是否是函数
      let b = function () {};
      Object.prototype.toString.call(b) === '[object Function]';//true
      //检验是否是数字
      let c = 1;
      Object.prototype.toString.call(c) === '[object Number]';//true

      4、通过Array.isArray()判断

    简单好用,而且对于多全局环境,Array.isArray() 同样能准确判断,但有个问题,Array.isArray() 是在ES5中提出,也就是说在ES5之前可能会存在不支持此方法的情况。

    let a = [1,2,3]
    Array.isArray(a);//true

      最终推荐方法

    if (!Array.isArray) {
      Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
      };
    }
  • 相关阅读:
    LeetCode 242. Valid Anagram (验证变位词)
    LeetCode 205. Isomorphic Strings (同构字符串)
    LeetCode 204. Count Primes (质数的个数)
    LeetCode 202. Happy Number (快乐数字)
    LeetCode 170. Two Sum III
    LeetCode 136. Single Number (落单的数)
    LeetCode 697. Degree of an Array (数组的度)
    LeetCode 695. Max Area of Island (岛的最大区域)
    Spark中的键值对操作
    各种排序算法总结
  • 原文地址:https://www.cnblogs.com/chenmeijiao/p/12060845.html
Copyright © 2011-2022 走看看