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

What are the methods of JavaScript type conversion

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to share with you what are the relevant knowledge points about the method of JavaScript type conversion, the content is detailed, and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

JavaScript addition rule

In JavaScript, the rule of addition is actually very simple, and there are only two cases:

The sum of numbers and numbers

Add a string to a string

All other types of values are automatically converted to these two types of values

In JavaScript, there are two types of values:

Original values are: undefined, null, Boolean (boolean), number (number), string (string), symbol

Object values: all other values are object type values, including arrays (arrays) and functions (functions)

Type conversion

The addition operator triggers three types of conversions: converting a value to a primitive value, converting to a number, and converting to a string, which corresponds to three abstract operations within the JavaScript engine: ToPrimitive (), ToNumber (), and ToString ()

Convert the value to the original value through ToPrimitive ()

ToPrimitive (input, PreferredType?)

The optional parameter PreferredType can be Number or String, which only represents the preference of a transformation. The conversion result does not have to be the type referred to by this parameter, but the conversion result must be an original value. If PreferredType is marked as Number, the following operations are performed to convert the entered value (§9.1):

If the value entered is already an original value, return it directly.

Otherwise, if the value entered is an object. The valueOf () method of the object is called. If the return value of the valueOf () method is an original value, the original value is returned.

Otherwise, the object's toString () method is called. If the return value of the toString () method is an original value, the original value is returned.

Otherwise, a TypeError exception is thrown.

If PreferredType is marked String, the order of the second and third steps of the conversion operation will be reversed. If there is no PreferredType, the value of PreferredType will be set automatically according to the rule: objects of type Date will be set to String, and other types of values will be set to Number.

Convert a value to a number through ToNumber ()

If the input value is an object, ToPrimitive (obj, Number) will be called first to convert the object to the original value, and then ToNumber () will be called to convert the original value to a number.

Convert a value to a string through ToString ()

If the input value is an object, ToPrimitive (obj, String) will be called first to convert the object to the original value, and then ToString () will be called to convert the original value to a string.

Demo

Var obj = {valueOf: function () {console.log ("valueOf"); return {}; / / No original value}, toString: function () {console.log ("toString"); return {}; / / No original value}}

When Number is called as a function (not as a constructor), the ToNumber () operation is called inside the engine:

Number (obj) / / outputvalueOftoStringUncaught TypeError: Cannot convert object to primitive valueString (obj) / / outputtoStringvalueOfUncaught TypeError: Cannot convert object to primitive value

Addition

Value1 + value2

When evaluating this expression, the procedure is as follows:

Convert the two operands to the original values (the following is a mathematical representation, not JavaScript code):

Prim1: = ToPrimitive (value1) prim2: = ToPrimitive (value2)

PreferredType is omitted, so the value of type Date is String, and the values of other types are Number.

If either prim1 or prim2 is a string, convert the other one to a string, and then return the result of the concatenation of the two strings

Otherwise, both prim1 and prim2 are converted to numeric types and their sum is returned.

[] + []

Output:''

[] will be converted to an original value, first try the valueOf () method and return the array itself (this):

> var arr = []; > arr.valueOf () = arrtrue

The result is not the original value, so call the toString () method and return an empty string (which is the original value). Therefore, the result of [] + [] is actually a concatenation of two empty strings.

> [] + {}'[object Object]'

{} + {}

Output: NaN

The JavaScript engine interpreted the first {} as an empty block of code and ignored it

The plus sign here does not represent the binary operator of addition, but a unary operator that converts the operands that follow it into numbers, exactly the same as the Number () function. For example:

+ {} Number ({}) Number ({} .toString ()) / / because {} .valueof () is not the original value Number ("[object Object]") NaN > {} + [] 0

{} ignore

+ [] = Number ([]) = Number ([] .toString ()) = Number (") = 0

Interestingly, Node.js 's REPL parses similar inputs differently from Firefox and Chrome (which uses the V8 engine like Node.js). The following input is parsed into an expression, and the result is more in line with our expectations:

> {} + {}'[object Object] [object Object]'> {} + []'[object Object] 'these are all the contents of this article entitled "what are the methods of JavaScript type conversion". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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