Many times we need to have data types in JavaScript ( Function , String , number, Undefined , Boolean and Object ) to make judgments. typeof
operators are provided in JavaScript to make judgments about these commonly used data types. But to use typeof
to determine whether the data is an array, it does not work. So how do you detect data in actual production is not an array?
Today's learning task is How to detect a data is not an array?
typeof operator
typeof can solve most of the data type detection, such as:
1Console.log (typeof function() {return;});//function2Console.log (typeof"A");//string3Console.log (typeof123);// Number4Console.log (typeofa);//undefined5Console.log (typeof true);//Boolean6Console.log (typeofNaN);// Number7Console.log (typeof! NaN);//Boolean8Console.log (typeof{Name: "Desert", Age: "37"});//Object9Console.log (typeof["Desert", "37"]);//ObjectTenConsole.log (typeof NULL);//Object
The above code example tells us, typeof {name:"大漠",age: "37"}
and typeof ["大漠","37"]
The return is all object
. The fact proves again that typeof
there is no way to detect the array, so this raises a question? How to tell if the data is an array type?
Detecting Array methods
Although typeof
the operator cannot detect an array, there are actually many ways to detect array methods. @Tom, @John, @Rick, @Ken, and @eric in an article in Quora, five different methods for detecting arrays are summarized. Next, let's learn and learn about these kinds of methods for detecting arrays.
of ECMAScript 5
isArray
Function
1 function IsArray (obj) {2 return Array.isarray (obj); 3 }4var// Create an array of 5// true
There is no doubt that this looks the most perfect solution because he is native. ECMAScript 5 will Array.isArray()
introduce JavaScript. But the compatibility makes you feel a little disappointed: ie9+, Firefox 4+, Safari 5+, Opera 10.5+ and chrome All implement this method, but the previous version of IE8 is not supported.
On this basis, the construction function is tested, and the detection process is very fast, but also very accurate. In fact, the use of us is too accurate. But at work it is not possible to determine that a variable is inherited from an array. In this way, testing the constructor to some extent is very necessary for us and is very useful:
1 function IsArray (obj) {2 return (typeof obj!== ' undefined ' && obj && obj.constructor = = = Array); 3 }
of the object itself
constructor
Property
In the above example, the constructor is instrumented with properties that are used on the image itself constructor
. The constructor
property returns a pointer to the function reference that created the object's prototype. You can also use this property to detect array types.
1 var arr = ["Desert", "W3cplus"]; 2 // true
instanceof
Operator
In addition to using the constructor property of the image itself to detect an array, you can also use the instanceof operator to detect an array.
instanceof
An operator can be used to determine whether the prototype property of a constructor exists on another prototype chain to detect the object. instanceof
This is to determine whether the preceding object is an instance of a later class or object.
Note: This operator has something to do with object-oriented in JavaScript, so you should understand the object-oriented in JavaScript first.
To recall instanceof
how operators are used. a instanceof b
, if returned true
, represents a
b
an instance of. So if it a instanceof Array
returns true
, does that mean a
the array type?
1 var arr = ["Desert", "W3cplus"]; 2 instanceof // true
Across
frame
Problems with instantiating objects
constructor and instanceof seem very good two ways to detect arrays, but there are still some loopholes, when you frame
come back to jump in multiple, these two methods are miserable. Because each frame
has its own set of execution environments, objects that cross- frame
instantiate do not share the prototype chain, and instanceof
constructor
the method of checking with operators and attributes naturally fails.
1 //Create an IFrame and add it to the DOM2 variframe = document.createelement (' iframe ');//Creating an IFRAME3Document.body.appendChild (IFRAME);//Add the created IFRAME to the body4Otherarray = window.frames[window.frames.length-1]. Array;5 vararr =NewOtherarray ("Desert", "W3cplus");//declaring an array ["Desert", "W3cplus"]6Console.log (arrinstanceofArray);//false7Console.log (Arr.constructor = = = Array);//false
Object native
toString
Detection
Object.prototype.toString behavior: First, obtain an internal property of the object [[Class]] , and then, based on this property, return a similar to "[Object Array]" string as a result (it should be known that the ECMA Standard is [[]]
used to represent a property that is used internally by the language and is not directly accessible externally, called an "internal attribute"). With this method, call
we can get the internal properties of any object [[Class]] and then convert the type detection to a string comparison to achieve our goal.
1 IsArray = function 2 return Object.prototype.toString.call (obj) = = "[Object Array]" 3 } 4 var arr = ["Desert", "W3cplus" 5 console.log (IsArray (arr)); //
Call changes the reference for toString to the object to be this
detected, returns the string representation of this object, and then compares whether this string is an instance of [object Array] to determine if it is Array
. Why not direct o.toString()
? Well, although Array
inherited from Object
, there will be toString
methods, but this method may be rewritten to meet our requirements, and Object.prototype is the tiger's butt, few people dare to touch it, So to a certain extent to ensure its "purity":)
The JavaScript standard document defines: [[Class]]
The value can be only one of the following strings: Arguments
, Array
, Boolean
Date
Error
Function
JSON
Math
Number
,,, Object
,,,,, RegExp
, String
.
Other methods
In addition to some of the methods described above for detecting arrays, there are:
@Rick provided by Waldron:
1 vararr = [A.];2 functionIsArray (ARG) {3 if(typeofarg = = = "Object" &&4("Join"inchArg &&typeofArg.join = = = "function") &&5("Length"inchArg &&typeofArg.length = = = "Number" ) ) {6 return true;7 }8 return false;9 }TenConsole.log (true, IsArray (arr));//true True OneConsole.log (false, IsArray ({join:true}) );//false False AConsole.log (false, IsArray ({join:function() {return false;}}) );//false False
@Shamasis provided by Bhattacharya:
1 varIsArray =function(SUBJ) {2 Try {3Subj && (subj.length = 1);4 return false;5 }6 Catch(er) {7 return true;8 }9 };Ten vararr = [A.]; OneIsArray (arr);//true
Provided by Douglas:
1 varIs_array =function(value) {2 returnValue &&3 typeofValue = = = ' object ' &&4 typeofValue.length = = = ' Number ' &&5 typeofValue.splice = = = ' function ' &&6! (value.propertyisenumerable (' length ')));7 };8 vararr = [A.];9Is_array (arr);//true
Best Detection method
In fact, there is no best detection method, only the most suitable detection method. A combination of the above methods to detect the array, slightly do some processing:
1 varIsArray = (function () {2 if(Array.isarray) {3 returnArray.isarray;4 } 5 varOBJECTTOSTRINGFN =Object.prototype.toString,6Arraytostringresult =Objecttostringfn.call ([]);7 8 return function(subject) {9 returnObjecttostringfn.call (subject) = = =Arraytostringresult;Ten }; One }()); A - vararr = []; -IsArray (arr);//true
The best way to do this is regardless of the Array.isArray‘是否能用,都可以回到对象原生
ToString 检测和对象原生
ToString ' detection.
JavaScript Learning notes: Detecting array methods