Description
Introducing JavaScript data types
Directory
- Objective
- Reference sources
- Front-facing technical requirements
- 6 Types of data for JavaScript
- What 6 types of data
- Undefined type
- Null type
- Boolean type
- Number Type
- String type
- Complex types
- The difference between the basic type and the reference type
- Some common questions about data types
- Why typeof null = = = ' object '
- The relationship of String,string,object,object,function,function
- Questions about string types and string types
- Difference between a function type and an object type
- The difference between = = and = = =
- The role of TypeOf
- The role of instanceof
- The role of Object.prototype.toString
- Why basic data types can use ToString and other operations
Preface reference Source
Walnuts, background shade, this article references the following sources
- JavaScript data types
- Know: Why is the value of typeof (null) inside JavaScript "Object"?
- Why can't I add properties and methods to basic types of variables in Sf:js?
Front-facing technical requirements
Before reading this article, it is recommended to read the following articles first
- JavaScript variables, values, and objects
6 Types of data for JavaScript
var variable = value; There are only two types, one is a basic type (similar to constant data) and one is a reference type (object)
First, we want to make clear that the data type of a JavaScript is the data type of the value. There are 6 types of data in JavaScript (5 basic data types, 1 reference types)
What 6 types of data
- Five basic data types (in fact, also referred to as Basic or primitive type)
Undefined,null,number,boolean,string
- A complex data type (reference type)
Object
Undefined type
The undefined type has only one value, that is, a special undefined. When you declare a variable with VAR but do not initialize it, the value of the variable is undefined. For example
var a;console.log (a===undefined);//true
Null type
The null type also has only one value, which is null, and from a logical point of view, a null value represents a null pointer (which is also the reason for detecting the return object using the TypeOf operator). If the defined variable is intended to be used to hold the object in the future, it is better to initialize the variable to null instead of the other value. This allows you to know whether the corresponding variable has saved a reference to an object as long as the null value is directly detected.
var a = Null;console.log (typeof a);//"Object"
In fact, in ECMAScript, the undefined value can be assumed to be derived from a null value, so undefined==null but Undefined!==null
Console.log (Undefined==null);//trueconsole.log (undefined===null);//false
Note that it is important to differentiate between the use of undefined and null. In general, the value of the variable is initially set to undefined (remember not to display the setting, which is set by the interpreter by default). The initial value of a reference object can generally be explicitly set to NULL. Or you can understand the initial value of the variable undefined as the base data type (the default setting), NULL as the initial value of the variable of the reference type (explicitly set)
Boolean type
The Boolean type has only two literal values of true,false. But these two values are not the same as numeric values, so true is not necessarily equal to 1, and false is not necessarily equal to 0.
To convert a value to a Boolean equivalent value, there are two scenarios:
- One is an explicit conversion-Call type conversion function Boolean ()
- One is an automatic conversion-if value in if (value) is automatically converted to a Boolean value
The following table is a worthwhile conversion between types and Boolean
Data Type |
the value converted to true |
value converted to false |
Boolean |
True |
False |
String |
Any non-empty string |
"" (empty string) |
Bumber |
Any non-0 numeric value (including infinity) |
0 and Nan |
Undefined |
No |
Undefined |
Null |
No |
Null |
Object |
Any object |
No |
Number Type
The number type is used to represent integers and floating-point numbers, and there is a special value (Nan-not a number, which is used to indicate that an operand that would have returned a numeric value did not return a count worth the case-to prevent throwing an error).
For example, in other languages the value ÷0 will cause errors, stop running, but in JS. 0/0, nan/0 will return NaN, other numbers/0 will return infinity, will not error.
Any operation involving a Nan will return Nan,js has a isNaN () function that can determine whether the received parameter is Nan, or whether the argument is Nan after it is converted to a number
Console.log (NaN + 1); Nan, any operation involving Nan will return NaNconsole.log (nan = = = Nan); False,nan is not equal to any value, including NaN itself Console.log (IsNaN (Nan)); True, is NaNconsole.log (IsNaN (' 10 ')); False, converted to digital 10console.log (IsNaN (true)); False, converted to digital 1console.log (IsNaN (null)); False, converted to digital 0console.log (IsNaN (undefined)); True to return NaNconsole.log (IsNaN (' Hello ')); True, cannot convert to digital console.log (0/0),//nan,0/0 returns NaNconsole.log (nan/0),//nan,nan/0 returns NaNconsole.log (1/0);//infinity, Other numbers/0 return Infinityconsole.log (' 1 '/0);//infinity, ' 1 ' successfully converted to digital Console.log (' 1a '/0);//nan, ' 1a ' converted to a digital failure, changed to NaNconsole.log ( infinity/0);//infinity, other digits/0 return Infinity
Note: The type of infinity is number (not the underlying data type)
There are two ways to convert a value of a non-number type to type #
- One is an implicit conversion, such as when a (*,/) operation is performed, the value of the remaining type is automatically converted to number type
Console.log ("1"),//12console.log ("1"/2),//0.5console.log ("1a"/2);//nan
- one is to show conversion-call number (), parseint (), parsefloat () method Transformation
The conversion rules for the number () function are as follows: (quoted from reference source)
- If it is a Boolean value, True and false are replaced with 1 and 0, respectively
- If it is a numeric value, simply pass in and return
- If it is a null value, returns 0
- If it is undefined, return Nan
- If it is a string, follow these rules:
- If the string contains only numbers, it is converted to a decimal value, that is, "1" becomes 1, "123" becomes 123, and "011" becomes 11 (leading 0 is ignored)
- If the string contains a valid floating-point format, such as "1.1", it is converted to the corresponding floating-point number (also ignoring the leading 0)
- If the string contains a valid hexadecimal format, such as "0xf", it is converted to a decimal integer value of the same size
- If the string is empty, convert it to 0
- If the string contains characters other than the above format, it is converted to Nan
- If it is an object, the valueof () method of the object is called, and the returned value is converted according to the preceding rule. If the result of the conversion is Nan, the object's ToString () method is called, and then the returned string value is converted in turn by the preceding rule.
Console.log (Number (")"),//0console.log (number (' a ')),//nanconsole.log (number (true)),//1console.log (Number (' 001 ') );//1console.log (number (' 001.1 '));//1.1console.log (number (' 0xf '));//15console.log (number (' 000xf '));//nanvar a = {};console.log (number (a));//nana.tostring = function () {return 2};console.log (number (a));//2a.valueof = function () { Return 1};console.log (number (a));//1
parseint () is often used to convert other types of values into shaping. parseint conversions differ from number () with the following specific rules
- parseint (Value,radius) has two parameters, the first parameter is the value that needs to be converted, and the second argument is the conversion (the value is between 2 ~ 36). If the parameter is less than 2 or greater than 36, parseint () returns NaN. ), if not passed (or a value of 0), the default is base 10 (if value starts with "0x" or "0X", 16 is the base)
- Note that in the case of the second parameter by default, if the string value that needs to be converted starts with 0, such as ' 070 ', in some environments, it is automatically converted to 8 binary 56, and some environments are automatically converted to 10 in 70. So in order to unify the effect, when we convert to 10, we pass the second parameter 10
- parseint Conversion Example
Console.log (parseint ("));//nanconsole.log (parseint (' a '));//nanconsole.log (parseint (' 1234blue '));// 1234console.log (parseint (true));//nanconsole.log (parseint (' 070 '));//70, but in some environments it is automatically converted to 8 binary 56console.log (parseint (' 070 ', 8)); /56console.log (parseint (' 001.1 ')),//1console.log (parseint (' 0xf ')),//15,16 (Console.log (' AF ', 16));// 175,16 Console.log (parseint (' AF '))//nanconsole.log (parseint (' 000xf '));//0var a = {};console.log (parseint (a));// nana.tostring = function () {return 2};console.log (parseint (a));//2a.valueof = function () {return 1};console.log ( parseint (a));//2
Parsefloat () Conversion rules are basically the same as parseint (), except for the following differences.
- Parsefloat () floating point is valid (but only the first. valid), such as "10.1" will be converted to 10.1; ' 10.1.1 ' will be converted into 10.1.
- Parsefloat () only defaults to 10, and ignores the 0 in front of the string, so there is no case of converting to 8 by default.
- Example
Console.log (parsefloat (' 1234blue ')),//1234console.log (parsefloat (' 1234blue ', 2));//1234console.log (' Parsefloat (' 0xA ');//0console.log (parsefloat (' 10.1 '));//10.1console.log (parsefloat (' 10.1.1 '));//10.1console.log (parsefloat (' 010 ')); /10
Because the number () function is complex and unreasonable when converting strings, it is more commonly used when working with integers parseint () function-be aware that the second parameter is passed 10 and more commonly used when handling floating-point numbers parsefloat ()
Also note that the direct calculation of floating point number has errors, so two floating-point numbers can not be used "=" to judge
var a=10.2;var b= 10.1;console.log (A-b = = = 0.1);//falseconsole.log (a-10.1 = = 0.1);//false, actually 0.09999999999999964cons Ole.log (a-0.1 = = = 10.1);//true
String type
The string type is used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, the string. The string can be represented by a single quotation mark (') or double quotation mark ("). The length of any string can be obtained by accessing its long property.
There are three ways to convert a value to a string.
- The first is the ToString () method with almost every value (except null and undefined not)
- ToString (RADIUS) has a parameter-cardinality, when the value of ToString is number, the parameter can take effect (can be converted to the corresponding input output, such as the 10.toString (8) output is 12)
- The second is an implicit conversion, such as the string + number (Null,undefined,object, etc.), which is converted to a string by default (if the object is added later, the ToString or valueof value of the object is returned)
- The third is through the conversion function string (), the string () conversion rule is as follows
- If the value has the ToString () method, the method (with no arguments) is called and the corresponding result is returned (note that the ValueOf () method is useless)
- Returns "NULL" if the value is null
- Returns "Undefined" if the value is undefined
- Example
var a = 10;var B = ' ten ' var c = {};console.log (a.tostring ());//10console.log (A.tostring (8));//12console.log (B.tostring (8 );//10, string cardinality is useless Console.log (string (c)),//[object Object]console.log (c);//[object Object]console.log (c + ' 1 ');//[ Object object]1c.valueof = function () {return 2};console.log (String (c));//[object Object]console.log (c);//[object Object],valueof useless Console.log (c + ' 1 ');//21, when implicit conversion, valueof functions c.tostring = function () {return 2};console.log (String (c) );//2console.log (c);//2,tostring functions Console.log (string (null));//"NULL", null and undefined can be a String () output Console.log ( Null.tostring ());//error, NULL and undefined cannot toString
Complex types
Complex types are reference types, which is what we often call JS objects (including ordinary object and function objects)
An object is actually a set of data and functions. An object can be created by executing the new operator followed by the name of the object type to be created. You can create a custom object by creating an instance of object and adding properties and/or methods to it. Such as
var o = new Object ();//Create a new custom object {}
That is, by removing the base type, the remaining reference type (including built-in objects, custom objects, and so on) is extended based on object
Each instance of object has the following properties and methods:
- constructor--holds the function for creating the current object
- hasOwnProperty (PropertyName)--Used to check for the existence of a given property in the current object instance, rather than in the prototype of the instance. where the attribute name (PropertyName) as a parameter must be specified as a string (for example: O.hasownproperty ("name"))
- isPrototypeOf (object)--Used to check if an incoming object is a prototype of another object
- propertyIsEnumerable (PropertyName)--Used to check whether a given property can use the For-in statement to enumerate
- ToString ()--Returns the string representation of an object
- ValueOf ()--Returns the string, numeric, or Boolean representation of the object. Usually the same as the return value of the ToString () method.
Reference to JS Prototype and prototype chain understanding
The difference between the basic type and the reference type
The biggest difference between the basic type and the reference type is that they are stored in different ways:
That is, if the value of the variable 1 becomes 102, the actual in-stack memory of 101 is not changed, but only in the stack memory of a new one, to store 102 of this constant. Then point the variable 1 to 102.
and the variable 2 because the stack memory is a pointer, the actual execution of the heap in memory data, so the value of the variable 2 can be arbitrarily changed (the data in the heap memory can be changed)
Some common questions about data types why typeof null = = = ' object '
This question has been raised by many people because, as a matter of fact, NULL is one of the five basic data types of JS, then typeof null and ===object? This is related to the historical reasons for ECMAScript. The reasons are as follows:
- JS in the five basic data types, in addition to NULL, the rest of the type is stored in the stack is a constant value (such as undefined storage is the undefined value, number type can be stored 0,1,2 ... etc.)
- As with the remaining four types, the null value is also stored in the stack, and there is only one value of NULL. And it happens logically that this is a pointer to an empty object (machine code null NULL pointer), so typeof returns an object. (for the following reasons, the answer is to the same name)
- JS type value is present in the three bit unit, 32 bits have 1-3 bits indicating the type TAG, the other bits represent the real value
- The tag bit that represents the object is exactly three bits low and is 0 (000:object). The data is a reference to an object.)
- And the null in JS is the machine code NULL NULL pointer, (0x00 is the most platforms). So the null pointer reference is added to the object tag or 0, and the final type is object.
- That's why number (NULL) ===0 ...
- There was a proposal to try to fix typeof = = = ' null ', but was rejected (as in the V8 engine can cause a lot of problems)
The relationship of String,string,object,object,function,function
Please distinguish between object,function,string and object,function,string.
Questions about string types and string types
JavaScript, the basic types have string,number, and so on, the complex types are also extended to string,number and so on. So what is the difference between the two? For example, a simple description of the difference between a string in a base type and a string in a complex type.
That is, the string type is placed in the stack memory (similar to constant), if the value of a variable of type string is changed to another string, then there is no change in the stack memory string, but a new string in the stack memory, And then change the reference to the variable.
Instead, the strign type of stack memory only has pointers to the heap memory data. So if the value is changed, the data content in the heap memory is modified directly, and the pointer in the stack memory does not change.
Difference between a function type and an object type
This point of knowledge is also a lot of people doubt, obviously there is only one kind of complex objects object, but why some function type of typeof return function, other objects return object?
- It is easy to understand that object,function,string is a JavaScript built-in function object, and typeof is the type that gets the function object, so it returns fucntion. The new object (), new String (), and so on, are constructed to create a typeof, so it returns object. The new Fucntion () construct is still a function object, so it returns fucntion
The function is the topmost constructor. It constructs all the objects in the system, including user-defined objects, system built-in objects, and even its own.
- About object and function can be understood like this
Null is the beginning of heaven and earth, and then null Object,object is the mother of all things. The object then has an attribute constructor, which happens to return the value of the function, so typeof object is a function. The function is then derived from object-based. Function.prototype._proto_ points to Object.prototype. (Function.constructor also returns the Function value)
- If you want to understand deeply, you need to have a certain understanding of the prototype and prototype chain in JS
Reference to JS Prototype and prototype chain understanding
- Example
function A () {};var b = function () {};var c = new function (); var d = new Object (); var e = new String (); var f = new Date (); Co Nsole.log (typeof a);//functionconsole.log (typeof B);//functionconsole.log (typeof c);//functionconsole.log (typeof Function);//functionconsole.log (typeof Object);//functionconsole.log (typeof D);//objectconsole.log (typeof String) ;//functionconsole.log (typeof e);//objectconsole.log (typeof Date);//functionconsole.log (typeof f);// Objectconsole.log (object instanceof function);//trueconsole.log (function instanceof object);//trueconsole.log (new Object () Instanceof object),//trueconsole.log (New object () instanceof function),//falseconsole.log (new function () instanceof function),//trueconsole.log (new function () instanceof Object),//truefunction foo () {};var foo = new Foo (); Console.log (foo instanceof foo),//trueconsole.log (foo instanceof Function),//falseconsole.log (foo instanceof Object) ;//trueconsole.log (foo instanceof Function);//trueconsole.log (foo instanceof Object);//true
The difference between = = and = = =
= = and = = = In JS has a comparative meaning, but the two have a very big difference, the difference is as follows:
- For basic simple types such as string,number,boolean, = = and = = are different
Because the values of different types are compared, = = will convert the comparison value to the same type of value after the value is seen equal. = = = will first determine the type, if the type is different, the result is unequal.
- For reference types, = = and = = are no different
Because this kind of comparison is "pointer address" comparison, different values, certainly false
- = = and = = are different for the underlying type and reference type comparison
for = = Converts a complex type to the underlying type, compares values, and, for = = =, false directly for different types
- Example
var a = 1;var B = True;console.log (A = = B); True, converted to the same type after the value equals console.log (a = = B); False, the first comparison type cannot, directly for falsevar a = {' Test ': ' 1 '};var b = {' Test ': ' 1 '};console.log (a = = B); False, compares the pointer address, unequal console.log (a = = B); False, compares the pointer address, unequal var a = ' one '; var b = new String (' one '); Console.log (A = = B); True to convert the advanced type string to the underlying type with a value equal to console.log (a = = B); False, because the type is different, direct to false
The role of TypeOf
JS variable value is loosely typed (weak type), can hold any type of data, JS built-in typeof can check the data type of a given variable, the possible return value is as follows:
- undefined:undefined type
- Boolean:boolean type
- String:string type
- Number:number type
- Object:null type or other reference type (object, remove function)
- Functions: This value is a function object, a special type in a reference type (you can think of the reference type as removing the function is Object)
Console.log (typeof ' Test '); ' String ' Console.log (typeof 101); ' Number ' Console.log (typeof true); ' Boolean ' Console.log (typeof undefined); ' Undefined ' console.log (typeof null); ' Object ' Console.log (typeof function () {}); ' function ' Console.log (typeof {}); Objectconsole.log (typeof new Date ()); Object
The role of instanceof
Instanceof is used to determine whether a variable is an instance of an object, primarily to determine whether the prototype property of a constructor exists on another prototype chain to examine the object.
- Instanceof can determine the built-in object type (based on Obejct object extension, such as array,date, etc.).
- You can determine the type of custom object, such as child and parent in the following
- But the simple type cannot be judged (because the essence is judged by the prototype, but the simple type is just a constant, not a reference object)
Identify built-in objects-Array, date, etc. console.log ([] instanceof array); Trueconsole.log (new string (' One ') instanceof string); Trueconsole.log (' one ' instanceof String); False, because 11 is a simple type//Identify custom object type and parent-child type function parent (x) {this.x = x;} function child (x, y) {Parent.call (this, x); this.y = y;} The child's prototype is pointed to the parent, indicating an inheritance relationship, when the child's construction becomes the parent's construct Child.prototype = new parent ();// The constructor is then swapped for child's own Child.prototype.constructor = Child;console.log (Child.prototype.constructor); The output constructor is child's own var person = new Child (1, 2); Console.log (person.x + ', ' + PERSON.Y); 1,2console.log (person instanceof child); Trueconsole.log (person instanceof Parent); true//does not recognize a simple type, since instanceof can only be a type Console.log (101 instanceof Number) that is based on object expansion. Error, number is not defined
The role of Object.prototype.toString
Object.prototype.toString exists primarily to address typeof and instanceof deficiencies, such as TypeOf's inability to identify built-in types (Array date, etc.), and instanceof does not recognize simple types. That's why we have this.
Object.prototype.toString can identify 5 simple types, as well as all built-in types (array.date, etc.), but do not recognize the custom object type
/** * @description by Object.prototype.toString to determine the type of incoming object * @param {object} obj */function type (obj) {//slice, for example, would return [ Object Number],slice filters out Numberreturn Object.prototype.toString.call (obj). Slice (8,-1). toLowerCase (); Console.log (Type (1)); Numberconsole.log (Type (' 1 ')); Stringconsole.log (Type (true)); Booleanconsole.log (type (undefined)); Undefinedconsole.log (type (null)); Nullconsole.log (Type (new Date ())); Dateconsole.log (Type ([])); Arrayconsole.log (Type ({})); Objectfunction Test (a) {this.a = A;} Console.log (Type (new Test (' 1 '))); Object, custom category can only be recognized as Object
Why basic data types can use ToString and other operations
In front of JS, there are basic types and reference types (object types, complex types, all kinds of arguments). Please note that there is an essential difference between the two.
- The value of a primitive type is not manipulated by itself, but with a "boxing", "unboxing" operation
var a = 10.1;console.log (a.tofixed (2)),//10.10, temporarily constructs a number object to operate, after the operation has been destroyed A.foo = ' test '; Console.log (A.foo); Undefined, because the value of a is not an object, the property cannot be bound
In the code above, a
a.xx
a temporary object of the corresponding wrapper type, such as number type, is created internally temporarily when operations are performed on the base type. and delegate the operation of the basic type to the temporary object, making the property access to the base type look like an object. However, after the operation is finished, the temporary object is thrown away, and the next time it is accessed, the temporary object will be re-established, although the modification of the previous temporary object will not be effective.
JavaScript build (ii)->JAVASCRIPT data types