Home > Article > Web Front-end > JavaScript method to determine whether a variable is an array (Array)_javascript skills
Today, the editor will compile some relevant knowledge about JavaScript to determine whether a variable is an array (Array). The topic will be expanded on through the following four points. The specific content is as follows:
1. Is typeof really that powerful? ?
//首先看代码 var ary = [1,23,4]; console.log(typeof ary); //输出结果是Object
The above method cannot detect in real time whether it is an array, but can only determine its type. Therefore, typeof is good at judging basic type data, but it cannot accurately test whether it is an array (the specific usage of typeof will be mentioned later) , now back to the topic)
2.instanceof judgment
var ary = [1,23,4]; console.log(ary instanceof Array)//true;
Judging from the output effect, it is quite satisfactory. It can accurately detect whether the data type is an array. Don’t be too happy. Let’s think about the shortcomings of this first. 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 这两段代码是一样的
This method is so sophisticated~~ It uses the prototype chain method, but this is compatible. In early versions of IE, __proto__ is not defined~ Moreover, this still has Limitations, let’s now summarize the limitations of the second and third methods
Summarize the limitations of the second and third methods
The variables judged by instanceof and constructor must be declared on the current page. For example, a page (parent page) has a frame, a page (child page) is referenced in the frame, and an ary is declared in the child page, and Assign it to a variable of the parent page, then judge the variable, Array == object.constructor; will return false;
Reason:
1. Array is reference data. During the transfer process, it is only the transfer of the reference address.
2. The address referenced by the Array native object of each page is different. The corresponding constructor of the array declared in the sub-page is the Array object of the sub-page; the parent page makes the judgment and uses the Array It is not equal to the Array of subpages; remember, otherwise it will be difficult to track the problem!
4. Common methods
var ary = [1,23,4]; function isArray(o){ return Object.prototype.toString.call(o)=='[object Array]'; } console.log(isArray(ary));
For specific usage of Object.prototype.toString, please refer to Usage of Object.prototype.toString
Okay, I will introduce to you so much about JavaScript’s method of determining whether a variable is an array (Array). Today I will mainly summarize these four types for you. If this article is not well written, please give me some advice. Thank you!