How to check if an object is an array?

后端 未结 30 2889
名媛妹妹
名媛妹妹 2020-11-21 06:31

I\'m trying to write a function that either accepts a list of strings, or a single string. If it\'s a string, then I want to convert it to an array with just the one item so

30条回答
  •  你的背包
    2020-11-21 06:53

    Imagine you have this array below:

    var arr = [1,2,3,4,5];
    

    Javascript (new and older browsers):

    function isArray(arr) {
      return arr.constructor.toString().indexOf("Array") > -1;
    }
    

    or

    function isArray(arr) {
      return arr instanceof Array;
    }
    

    or

    function isArray(arr) {
      return Object.prototype.toString.call(arr) === '[object Array]';
    }
    

    then call it like this:

    isArray(arr);
    

    Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

    Array.isArray(arr);
    

    jQuery:

    $.isArray(arr);
    

    Angular:

    angular.isArray(arr);
    

    Underscore and Lodash:

    _.isArray(arr);
    

提交回复
热议问题