Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of knowledge related to JavaScript data types

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "summary of knowledge related to JavaScript 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!

Data types in js

What are the data types in javascript?

There are seven built-in data types in JavaScript, including basic and object types.

Basic type

The basic types are divided into the following six types:

String (string)

Boolean (Boolean)

Number (digital)

Symbol (symbol)

Null (null)

Undefined (undefined)

Note:

String, number, boolean and null undefined are collectively referred to as primitive types (Primitive), which represent basic types that can no longer be subdivided.

Symbol is a new data type in ES6. Symbol represents the value of * *, which is generated by calling the Symbol function. Because the generated symbol value is of the original type, the Symbol function cannot call new.

Null and undefined are generally considered special values, and the only values of these two types are themselves.

Object Typ

Object types are also called reference types, and array and function are subtypes of objects. An object is logically an unordered collection of attributes and a container for storing various values. Object values store reference addresses, so unlike the immutable properties of base type values, object values are mutable.

Js weakly typed language

Interviewer: what is your understanding that javascript is a weakly typed language?

JavaScript is a weakly typed language, and when JavaScript declares a variable, there is no predetermined type, and the type of the variable is the type of its value, that is to say, the current type of the variable is determined by its value. To exaggerate, the String of the last second may be a Number type the next, and some operations may have taken place in this process. Although the characteristic of weak type, which does not need to determine the type in advance, brings us convenience and trouble at the same time, we must master the principle of type conversion in order to make full use of this feature.

Cast rules in js

Interviewer: casting is a very bug-prone point in javascript. Do you know the rules for casting?

Note: the rules * * will work better with the following when the conversion occurs.

ToPrimitive (convert to original value)

ToPrimitive does not convert primitive types, but only for reference types (object). Its purpose is to convert reference types (object) to non-object types, that is, primitive types.

The ToPrimitive operator takes a value and an optional expected type as an argument. The ToPrimitive operator converts the value to a non-object type, and if the object has the ability to be converted to more than one primitive type, an optional expected type can be used to imply that type.

The original type of the converted result is determined by the expected type, which is actually the type we pass. It's clearer to look directly below.

The ToPrimitive method looks something like this as follows.

/ * * @ obj object to be converted * @ the original data type to which type expects to be converted. Optional * / ToPrimitive (obj,type)

Description of different values of type

Type is string:

First call the toString method of obj, if it is the original value, then return, otherwise proceed to step 2

Call the valueOf method of obj, if it is the original value, then return, otherwise proceed to step 3

Throw a TypeError exception

Type is number:

First call the valueOf method of obj, if it is the original value, then return, otherwise proceed to step 2

Call the toString method of obj, if it is the original value, then return, otherwise step 3

Throw a TypeError exception

Type parameter is empty

If the object is Date, type is set to String

Otherwise, type is set to Number

Special description of Date data type:

For the Date data type, we expect to get the string after it is converted to time rather than the millisecond value (timestamp). If it is number, we will get the corresponding millisecond value, obviously the string uses more.

Other types of objects can be operated according to the type of value.

ToPrimitive summary

The original type to which ToPrimitive is converted depends on the optional type,type parameter. If specified, it is converted according to the specified type. If not specified, there are two cases by default according to practical conditions: Date is string, and other objects are number. So when the type type will be specified depends on the following two conversions.

ToString

Object.prototype.toString ()

The toString () method returns a string that represents the object.

Each object has a toString () method that is automatically called when the object is represented as a text value or when the object is referenced as a desired string.

Keep in mind here that valueOf () and toString () are called on their own in certain situations.

ValueOf

The Object.prototype.valueOf () method returns the original value of the specified object.

JavaScript calls the valueOf () method to convert the object to values of the original type (numeric, string, and Boolean). But we rarely need to call this function ourselves, and the valueOf method is usually called automatically by JavaScript.

ValueOf implementation of different built-in objects:

String = > returns a string value

Number = > returns a numeric value

Date = > returns a number, that is, the time value, and the content in the string depends on the specific implementation

Boolean = > returns the th value of Boolean

Object = > returns this

It will be clearer against the code:

Var str = new String ('123'); console.log (str.valueOf ()); / / 123var num = new Number (123); console.log (num.valueOf ()); / 123var date = new Date (); console.log (date.valueOf ()); / / 1526990889729 var bool = new Boolean (' 123'); console.log (bool.valueOf ()); / / true var obj = new Object ({valueOf: () = > {return 1}) console.log (obj.valueOf ()); / / 1

Number

Number operator conversion rules:

Convert null to 0

Convert undefined to NaN

True is converted to 1, and false is converted to 0

String conversion follows the rule of numeric constant. If conversion fails, NaN is returned.

Note: the object needs to be converted to the original value first, and the ToPrimitive transformation is called. Type is specified as number, and then go back to ToPrimitive for conversion.

String

String operator conversion rules

Convert null to 'null'

Convert undefined to undefined

Convert true to 'true',false to' false'

Digital conversion follows general rules, and minimax numbers use exponential form.

Note: the object needs to be converted to the original value first, call the ToPrimitive conversion, and type will be specified as string, and go back to ToPrimitive for conversion (there are conversion rules to ToPrimitive above).

String (null) / / 'null' String (undefined) / /' undefined' String (true) / / 'true' String (1) / /' 1' String (- 1) / /'- 1' String (0) / /'0' String (- 0) ) / /'0' String (Math.pow (1000 String 10)) / / '1ebegin30' String (Infinity) / /' Infinity' String (- Infinity) / /'- Infinity' String ({}) / /'[object Object] 'String ([1 [2koala',1 3]) / '1min2' String (['koala',1]) / / koala,1

Boolean

ToBoolean operator conversion rules

Except that the following 6 values are converted to false, all of them are true:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Undefined

Null

-0

0 or + 0

NaN

'' (empty string)

All values except false values are true values. The conversion result of all objects, including empty objects, is true, and even the Boolean object new Boolean (false) corresponding to false is true.

Boolean (undefined) / / false Boolean (null) / / false Boolean (0) / / false Boolean (NaN) / / false Boolean ('') / / false Boolean ({}) / / true Boolean ([]) / / true Boolean (new Boolean (false)) / / true

Application of js conversion rules in different scenarios

The interviewer asked: I know the rules of what to convert into, but under what circumstances and what kind of conversion happens?

When is it automatically converted to string type

Under the premise of no object

The automatic conversion of strings mainly occurs in the addition operation of strings. When one value is a string and the other is a non-string, the latter is converted to a string.

'2' + 1 / /' 21''2' + true / / "2true"'2' + false / / "2false"'2' + undefined / / "2undefined"'2' + null / / "2null"

When there is an object and is associated with an object +

/ / object var obj2 of toString = {toString:function () {return 'a'}} console.log ('2'+obj2) / / output result 2a / / regular object var obj1 = {avell, baza2} console.log (' 2'+obj1) / / output result 2 [object Object] / / several special objects'2' + {} / / "2 [object Object]"'2' + [] / / "2"'2' + function () {} / / "2function () {}"'2' + ['koala',1] / / 2koala1

A detailed example of the following '2'+obj2 is as follows:

On the left, the original value of string,ToPrimitive does not change after conversion.

During the conversion on the right, the original value is also converted according to ToPrimitive. Since the specified type is number, ToPrimitive conversion is called obj2.valueof (), and the result is not the original value. Proceed to the third step.

Call toString () return 'a'

There is a string on both sides of the symbol, and the + operator uses the String rule to convert to string type for splicing.

Output result 2a

A detailed example of the following '2'+obj1 is as follows:

String,ToPrimitive on the left does not change after it is converted to the original value.

During the conversion on the right, the original value is also converted according to ToPrimitive. Since the specified type is number, ToPrimitive conversion is called obj2.valueof () to get {a: 1, b: 2}.

Call toString () return [object Object]

There is a string on both sides of the symbol, and the + operator uses the String rule to convert to string type for splicing.

Output result 2 [object Object]

The conversion rules of several special objects in the code are basically the same, so if you don't explain them one by one, you can think about the process.

Note: whether it is an object or not, there is a process of conversion to the original value, that is, the ToPrimitive conversion, but the object type will not change until the original type is converted.

Possible errors in the development of string type conversion:

Var obj = {width: '100'}; obj.width + 20 / / "10020"

Expected output 120 actual output 10020

When is it automatically converted to Number type

When there is an addition operator, but there is no String type, it will be converted to Number type first.

Example:

True + 0 / / 1 true + true / / 2 true + false / / 1

Except for the addition operator, all operators automatically convert the operation to a numeric value.

Example:

'5' -' 2' / / 3'5' *'2' / / 10 true-1 / / 0 false-1 / / 1' 1'-1 / / 0'5' * [] / / 0 false / 5' / 0 'abc'-1 / / NaN null + 1 / / 1 undefined + 1 / / NaN / / unary operator (note) +' abc' / NaN-'abc '/ / NaN + true / / 1-false / / 0

Note: null is 0 when converted to numeric value, while undefined is NaN when converted to numeric value.

The judgment equal sign is also put in Number for special instructions.

The = = abstract equality comparison differs from the + operator in that String no longer takes precedence, but Number takes precedence.

The following is an example of x = y

If both XBI y are number, compare directly.

There's nothing to explain.

1 = 2 / / false

If an object exists, ToPrimitive () type converts it for number, and then makes a later comparison

Var obj1 = {valueOf:function () {return'1'}} 1 = = obj1 / / true / / obj1 to the original value Call obj1.valueOf () / / return the original value'1' / / '1'toNumber to get 1 and then compare 1 = 1 [] =! [] / / true / / [] as object ToPrimitive to get''/ /! [] as boolean conversion to get 0 / /'= = 0 / / convert to 0 / / true

If boolean exists, convert boolean to 1 or 0 according to ToNumber, and then make a later comparison.

/ / boolean is first converted to number, and according to the above rule, 1 / / 3 = = 1 false / / 0 = = 0 true 3 = = true / / false'0' = = false / / true

4. If x is string,y, convert number,x to number for comparison.

/ /'0' toNumber () get 0 / / 0 = = 0 true'0' = = 0 / / true

When to perform Boolean conversion

Boolean comparison

If (obj), while (obj), etc., or ternary operators can only contain Boolean values

Each value in the conditional part is equivalent to false, and after using the negative operator, it becomes true

If (! undefined & &! null & &! 0 & &! NaN & &!') {console.log ('true');} / / true / / the following two cases will also be converted to Boolean expression? True: false!! Expression

Data type judgment in js

The interviewer asked: how to judge the data type? How to tell whether a value is an array type or an object?

Three ways, typeof, instanceof and Object.prototype.toString ()

Typeof

Determine which basic type a value belongs to by the typeof operator.

Typeof 'seymoe' / /' string' typeof true / / 'boolean' typeof 10 / /' number' typeof Symbol () / / 'symbol' typeof null / /' object' cannot determine whether it is null typeof undefined / / 'undefined' typeof {} / /' object' typeof [] / / 'object' typeof (() = > {}) / /' function'

The output of the above code can be seen

There is an error in the judgment of null, and the result

If you use typeof,null, the result is object

The operator determines the object type and its subtypes, such as functions (callable objects), arrays (ordered indexed objects), and so on, and gets the result of object except the function.

To sum up, we can see that typeOf has some shortcomings in judging types, in the case of object subtypes and null.

Instanceof

The object type can also be determined by the instanceof operator, which is based on testing whether the prototype of the constructor appears on the prototype chain of the detected object.

[] instanceof Array / / true ({}) instanceof Object / / true (() = > {}) instanceof Function / / true

Note: instanceof is not * either.

For example:

Let arr = [] let obj = {} arr instanceof Array / / true arr instanceof Object / / true obj instanceof Object / / true

In this example, the arr array is equivalent to an instance of new Array (), so arr.__proto__ = = Array.prototype, and because Array belongs to the Object subtype, that is, Array.prototype.__proto__ = Object.prototype, the Object constructor is on the prototype chain of arr. So instanceof still can't tell gracefully whether a value belongs to an array or a normal object.

There is another point to note. Some developers will say Object.prototype.__proto__ = = null, doesn't it mean that arr instanceof null should also be true? in fact, this statement will report an error indicating that the parameter on the right should be an object, which also confirms that the result of typeof null is that object is really just a bug in javascript.

Object.prototype.toString () can be said to be a * solution to determine the data type in JavaScript. For specific usage, please see the following code:

Object.prototype.toString.call ({}) / /'[object Object] 'Object.prototype.toString.call ([]) /' [object Array] 'Object.prototype.toString.call (() = > {}) / /' [object Function] 'Object.prototype.toString.call (' seymoe') / /'[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 (null) / /' [object Null] 'Object.prototype.toString.call (undefined) / /' [object Undefined] 'Object.prototype.toString.call ( New Date () /'[object Date] 'Object.prototype.toString.call (Math) / /' [object Math] 'Object.prototype.toString.call (new Set ()) / /' [object Set] 'Object.prototype.toString.call (new WeakSet ()) / /' [object WeakSet] 'Object.prototype.toString.call (new Map ()) / /' [object Map] 'Object. Prototype.toString.call (new WeakMap ()) / /'[object WeakMap]'

We can find that this method can return the corresponding exact object type when passing in any type of value. Although the usage is simple and clear, there are several points that need to be understood:

The essence of this method is to get the internal properties of the object [[Class]] by relying on the Object.prototype.toString () method.

Passing in the original type can determine the result because the value is wrapped.

Null and undefined can output results that are processed by the internal implementation.

Summary related to NaN

The concept of NaN

NaN is a property of a global object, NaN is a property of a global object, and NaN is a special Number type.

When will you return to NaN (the second question at the beginning is also solved)

Infinity divided by infinity

Do the square operation for any negative number

Arithmetic operators are used with operands that are not numbers or cannot be converted to numbers

Parse a string into a number

Some examples:

Infinity / Infinity; / / divide infinity by infinity Math.sqrt (- 1); / / square any negative number'a'-1; / / use'a' * 1;'a' / 1; parseInt ('a') with operands that are not or cannot be converted to numbers. / / the string is parsed into numeric parseFloat ('a'); Number ('a'); / / NaN 'abc'-1 / / NaN undefined + 1 / / NaN / / unary operator (note) +' abc' / / NaN-'abc' / / NaN

Misunderstanding

The difference between toString and String

ToString

ToString () can convert all data to strings, but null and undefined cannot be converted.

Console.log (null.toString ()) / / error TypeError: Cannot read property 'toString' of null console.log (undefined.toString ()) / / error TypeError: Cannot read property' toString' of undefined

ToString () can write numbers in parentheses, representing the binary

Binary: .toString (2)

Octal: .toString (8)

Decimal: .toString (10)

Hex: .toString (16)

String

String () can convert null and undefined to strings, but cannot convert them to system strings

Console.log (String (null)); / null console.log (String (undefined)); / / undefined "Summary of knowledge related to JavaScript data types" ends here. 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: 0

*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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report