Because javascript is a weak type of language, and everything in javascript is essentially an object, it is not easy for us to directly determine whether the object is an array, next, I will sort out the implementation methods for js to determine whether it is an array.
Method for judging javascript Arrays
The Code is as follows: |
Copy code |
Var is_array = function (){ Return value && Typeof value === 'object '&& Value. constructor === Array; } |
We know that javascript is a weak type of language, and everything in javascript is essentially an object. Therefore, it is very important to check the object type in javascript.
Here, I will introduce two methods that are frequently used in js for type detection.
The first method is to use the "typeof" operator, which may be known to everyone. One of the following six strings is used for type detection: "number", "boolean", "object", "number", "function ", "string ". Yes. We can detect the vast majority of object types using this operator. However, here is an exception: when using arrays. The difference between arrays and objects in javascript itself is confusing. The typeof operator reports that arrays and objects are of the "object" type. Therefore, javascript does not have a good yield mechanism for distinguishing arrays and objects.
For example:
The Code is as follows: |
Copy code |
Var arr = [1, 2, 4, 5] Var obj = {"name": "xiaoming", "sex": "nan "}; Alert (typeof arr) // returns "object" Alert (typeof obj) // returns "object" |
So how can we identify this special situation?
Here is the second common type check method I want to talk about: "constructor" attribute.
In javascript, any object has a constructor attribute, which references the original function used to construct the object.
The following sample code illustrates the usage of this method:
The Code is as follows: |
Copy code |
Var num = 11, str = "abc", obj = {num: 11}, arr = [1, 2, 3]; Alert (num. constructor === Number); // true Alert (str. constructor === String); // true Alert (obj. constructor === Object); // true Alert (arr. constructor === Array); // true |
As you can see, when using constructor, the Array does not return an object, but an Array with a clear meaning.
The following table shows the results of performing type checks on different types of objects using the preceding two methods.
Variable typeof variable. construtor
{An: "object"} object Object
["An", "array"] object Array
Function () {} function Function
"A string" string String
55 number
True boolean Boolean
New User () object User