In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the methods of JS data types". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
In the ECMAScript specification, seven data types are defined, which are divided into basic types and reference types, as follows:
Basic types: String, Number, Boolean, Symbol, Undefined, Null reference types: Object
The basic type is also known as the simple type, because it occupies a fixed space and is a simple data segment, in order to improve the query speed of variables, it is stored in the stack, that is, access by value.
A reference type is also called a complex type, and because its value changes, it cannot be stored in the stack, otherwise it will slow down the query speed of the variable, so its value is stored in the heap, and the value stored in the variable is a pointer to the memory of the storage object, that is, access by address. In addition to Object, reference types include Function, Array, RegExp, Date, and so on.
Given that ECMAScript is loosely typed, a means is needed to detect the data type of a given variable. JavaScript also provides a variety of ways to solve this problem, but unfortunately, the results from different methods are uneven.
Here are four commonly used methods, and a simple analysis of the problems existing in each method.
1 、 typeof
Typeof is an operator with a unary expression to the right and returns the data type of the expression. The returned results are expressed in this type of string (all lowercase letters), including the following seven types: number, boolean, symbol, string, object, undefined, function, and so on.
Typeof'';// string is valid
Typeof1;// number is valid
TypeofSymbol (); / / symbol is valid
Typeoftrue;//boolean is valid
Typeofundefined;//undefined is valid
Invalid typeofnull;//object
Invalid typeof []; / / object
TypeofnewFunction (); / / function is valid
Invalid typeofnewDate () / / object
Invalid typeofnewRegExp () / / object
Sometimes, the typeof operator returns confusing but technically correct values:
For basic types, with the exception of null, correct results can be returned.
For reference types, the object type is returned except for function.
For null, returns the object type.
Returns the function type for function.
Among them, null has its own data type Null, and the array, date, and regularity in the reference type all have their own specific types, and typeof's handling of these types only returns the Object type at the top of its prototype chain, no mistake, but not the result we want.
2 、 instanceof
Instanceof is an instance used to determine whether An is B, the expression is: An instanceof B, if An is an instance of B, true is returned, otherwise false is returned. One thing to note here is that instanceof detects prototypes, and we use a piece of pseudo code to simulate its internal execution:
Instanceof (A _ maeb) = {
VarL = A. protoplast _
VarR = B.prototype
If (L = = R) {
/ / the internal attribute _ _ proto__ of A points to the prototype object of B
Returntrue
}
Returnfalse
}
As can be seen from the above process, when the proto of A points to the prototype of B, An is considered to be an instance of B. Let's look at a few more examples:
[] instanceof Array;// true
{} instanceof Object;// true
NewDate () instanceof Date;// true
Function Person () {}
NewPerson () instanceof Person
[] instanceof Object;// true
NewDate () instanceof Object;// true
NewPerson instanceof Object;// true
We found that although instanceof can tell that [] is an instance of Array, it thinks that [] is also an instance of Object. Why?
Let's analyze the relationship among [], Array, and Object:
You can tell from instanceof that [] .proto points to Array.prototype, while Array.prototype.proto points to Object.prototype, and finally Object.prototype.proto points to null, marking the end of the prototype chain. As a result, [], Array, and Object form a prototype chain inside:
As can be seen from the prototype chain, the proto of [] points directly to Array.prototype and indirectly to Object.prototype, so according to the judgment rule of instanceof, [] is an instance of Object. In turn, similar new Date () and new Person () form a corresponding prototype chain. Therefore, instanceof can only be used to determine whether two objects belong to an instance relationship, not to determine which type an object instance belongs to.
The problem with the instanceof operator is that it assumes only one global execution environment. If the page contains multiple frames, there are actually more than two different global execution environments, resulting in more than two different versions of the constructor. If you pass an array from one frame to another, the array passed in has a different constructor from the array created natively in the second frame.
Variframe = document.createElement ('iframe')
Document.body.appendChild (iframe)
XArray = window.frames [0] .Array
Vararr = newxArray (1pr 2je 3); / / [1je 2je 3]
Arr instanceof Array;// false
If (Array.isArray (value)) {
/ / A pair of arrays perform some operations
}
Array.isArray () essentially detects the [[Class]] value of the object, and [[Class]] is an internal property of the object, which contains the type information of the object in the format of [object Xxx], and Xxx is the corresponding specific type. For arrays, the value of [[Class]] is [object Array].
3 、 constructor
When a function F is defined, the JS engine adds a prototype prototype to F, then adds a constructor attribute to the prototype and points to a reference to F. As follows:
When var f = new F () is executed, F is treated as a constructor, f is an instance object of F, and the constructor on the F prototype is passed to f, so f.constructor = = F
It can be seen that F uses the constructor on the prototype object to reference itself. When F is used as the constructor to create the object, the constructor on the prototype is inherited to the newly created object. From the perspective of prototype chain, the constructor F is the type of the new object. The point of this is to make new objects have traceable data types after they are born.
Similarly, built-in objects in JavaScript do the same when built internally:
Details:
Null and undefined are invalid objects, so there is no constructor, and these two types of data need to be judged in other ways. two。 The constructor of the function is unstable, which is mainly reflected in the custom object. When the developer rewrites the prototype, the original constructor reference will be lost and the constructor will default to Object.
Why did it become Object?
Because prototype is reassigned as a {}, which is the literal quantity of new Object (), new Object () passes the constructor on the Object prototype to {}, that is, Object itself.
Therefore, in order to standardize development, it is generally necessary to re-assign values to constructor when rewriting object prototypes to ensure that the types of object instances are not tampered with.
4 、 toString
ToString () is the prototype method of Object, which is called and returns the [[Class] of the current object by default. This is an internal property in the format [object Xxx], where Xxx is the type of object.
For Object objects, a direct call to toString () returns [object Object]. For other objects, you need to call through call / apply to return the correct type information.
Object.prototype.toString.call (''); / / [object String]
Object.prototype.toString.call (1); / / [object Number]
Object.prototype.toString.call (true); / / [object Boolean]
Object.prototype.toString.call (Symbol ()); / / [object Symbol]
Object.prototype.toString.call (undefined); / / [object Undefined]
Object.prototype.toString.call (null); / / [object Null]
Object.prototype.toString.call (newFunction ()); / / [object Function]
Object.prototype.toString.call (newDate ()); / / [object Date]
Object.prototype.toString.call ([]); / / [object Array]
Object.prototype.toString.call (newRegExp ()); / / [object RegExp]
Object.prototype.toString.call (newError ()); / / [object Error]
Object.prototype.toString.call (document); / / [object HTMLDocument]
Object.prototype.toString.call (window); / / [object global] window is a reference to the global object global
This is the end of the content of "what are the methods of JS data types". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 222
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.