Today small make up some about the JavaScript to determine whether the variables are arrays (array) related knowledge, mainly through the following four points to start the topic, the specific content as follows:
1. Is typeof really that bad??
First look at the code
var ary = [1,23,4];
Console.log (typeof ary); Output is Object
The above method is not able to detect in real time is an array, can only judge its type, so said TypeOf to judge the basic type of data is very good, but can not accurately test whether the array (typeof specific usage later mentioned, now return to the topic)
2.instanceof judgment
var ary = [1,23,4];
Console.log (ary instanceof Array)//true;
From the output of the effect, or quite satisfactory, can accurately detect whether the data type is an array, do not be happy too early, we first think of this shortcoming, we continue to say 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 the same
This way to open up very tall Oh ~ ~, the use of the prototype chain method, but, this is compatible oh, in IE earlier version of the __proto__ is not defined oh ~ and, this still has limitations, we are now to summarize the 2nd method and the 3rd method limitations
Summarize the limitations of the 2nd and 3rd methods
Instanceof and constructor to judge the variables, must be declared on the current page, for example, a page (parent page) has a frame, the frame refers to a page (subpage), in the child page declared a ary, and assign it to the parent page of a variable, then judge the variable, Array = = Object.constructor; returns false;
Reason:
1, the array belongs to the reference data, in the transfer process, only refers to the transfer of the address.
2, each page of the array native object refers to the address is not the same, in the child page declared array, the corresponding constructor, is a child page of the array object, the parent page to judge, the use of the array is not equal to the child page array; Remember, it is difficult to track the problem!
4. General methods
var ary = [1,23,4];
function IsArray (o) {return
Object.prototype.toString.call (o) = = ' [Object Array] ';
}
Console.log (IsArray (ary));
For specific Object.prototype.toString use, refer to the use of Object.prototype.toString
All right, about JavaScript. To determine whether a variable is an array of methods (array) to introduce you so much, today's main summary of these four kinds, this article is not good to write a lot of heroes please teach, thank you!