JavaScript method to determine whether a variable is an array

  • 2021-01-02 21:46:19
  • OfStack

Today, this site will give you some knowledge about javascript to determine whether the variable is an array (Array), mainly through the following four points to expand the topic, specific content is as follows:

1. Is typeof really that good?


// So let's look at the code 
var ary = [1,23,4];
console.log(typeof ary); // The output is Object

The above method does not detect whether it is an array in real time, only its type can be determined, so it is good for typeof to determine the basic type of data, but it cannot accurately test whether it is an array. (The specific usage of typeof will be mentioned later, now let's get back to the topic.)

2. instanceof judgment


var ary = [1,23,4];
console.log(ary instanceof Array)//true;

From the output effect, or quite satisfactory, can accurately detect whether the data type is an array, do not rejoice too early, we first think about the disadvantages of this, let's move on to the third method

3. Prototype chain method


var ary = [1,23,4];
console.log(ary.__proto__.constructor==Array);//true
console.log(ary.constructor==Array)//true  These two pieces of code are 1 The sample of 

This approach makes sense, using the prototype chain approach, but, again, it's compatible, with no definition in the earlier versions of IE/ES24en__ and still has limitations, let's summarize the limitations of method 1, 2, and 3 now

The limitations of the second method and the third method are summarized

The variable judged by instanceof and constructor must be declared in the current page. For example, there is a frame for 1 page (parent page), which refers to 1 page (child page), declares 1 ary in the child page, and assigns it to a variable of the parent page, then the variable is judged, Array == object. constructor; It returns false;

The reason:

1. array belongs to reference data. In the process of passing, it is only the passing of reference address.

2. The address referenced by the Array native object of each page is not the same. The array declared in the sub-page is the corresponding constructor of the Array object of the sub-page; The parent page is used to judge, Array is not equal to the child page Array; Remember, otherwise it's hard to track the problem!

4. The general approach


var ary = [1,23,4];
function isArray(o){
return Object.prototype.toString.call(o)=='[object Array]';
}
console.log(isArray(ary));

For the usage of ES53en. prototype. toString, please refer to Object. prototype. toString

Well, JavaScript to determine whether the variable is an array of methods (Array) to introduce so much to you, today I mainly give you the summary of the four kinds, this article is not good also please advise you more, thank you!


Related articles: