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

When will the automatic conversion of JavaScript occur?

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

Share

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

This article mainly introduces when the JavaScript will be automatically converted, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

JavaScript is free to perform data type conversions and provides a variety of ways to convert explicitly. But in more cases, it is automatically converted by JavaScript, of course, these conversions follow certain rules, so it is necessary to understand the rules of free conversion of data types.

Data type

When it comes to data type conversion, you have to mention JavaScript's data types: primitive types (Number, String, Boolean, undefined, null, Symbol), object types (Object). Of course, Object can be subdivided into Array, Date, RegExp and so on.

Since there are so many data types, each data type must have a specific purpose, so what if the data type of the value provided does not match the expectation?

For example, I need to use the boolean value in the control statement, but the value provided is string. Of course, we can explicitly convert Boolean (a: string), but from daily experience, we know that it doesn't need to be so complicated, and we can use this string-type variable directly in the control statement to achieve the desired results. As follows:

It can be seen that automatic conversion is much more convenient, but what rules are followed in this process?

Automatic conversion when will automatic conversion occur?

The rhino book says that when JavaScript expects to use a Boolean value, you can provide any type of value, and JavaScript will convert the type as needed. Some values (true values) are converted to true, and some values (false values) are converted to false. The same applies to other types: if JavaScript expects to use a string, it converts the given value to a string. If JavaScript expects a number, it converts the given value to a number (if the conversion result is meaningless, it will return NaN).

In short: JavaScript has some statements / operators that require data types, but automatic type conversions occur when what we provide is not as expected.

Expressions and operators that expect data types

Expect boolean type: if, do while, while do, & &, | |,! (and or non-logical expression),?: (ternary operator)

Expect number type: +-* /% (arithmetic operator), +-- (increment / decrement operator), > > =, > =,

< 、 、>

=,

< 、 "11" // true 字符串比较 3 >

"11" / / false 11 is converted to the number true >'0' / / true true and'0' are converted to the number 2, and the object is also converted to the original value (but the Date object here also calls valueOf first and returns the number of milliseconds, the other is the same as the above +), if a word after conversion is not a string Then both values also need to be converted to the number 1000 > new Date () / / false 100000000000000000000000 > new Date () / / true date object to the number "1000000000000000000000000" > new Date () / / true left value is also converted to the number '11' > ["3"] / / false array into a string along with the date object, so here is the string comparison

It is important to note that as long as one of the values in the conversion to a number is NaN, the result of the comparison must be false.

=,! =

The = =,! = (no) equality operators are not strictly compared, so if the two operands are not of the same type, some type conversions are attempted and then compared. There are the following rules and type conversions:

One value is undefined, and the other is null, then it is equal.

If a value is a number and a value is a string, the string is converted to a number for comparison

True and false are converted to 1 and 0, respectively

One value is a string or number, and the other is an object, which is converted to the original value (the Date class only calls toString, and the others are the same as before), and then compare.

The other comparisons are all false.

Null = = undefined / / true 1null = = 0 / / false 51 = ='1' / / true 21 = = true / / true 32 = = true / / false 31 = = [1] / / true 4x1' = = ['1'] / / true 4 array to string 1 = = ['1'] / / true 4 array to string and then to digital object wrapper

There is also an automatic conversion that is easily overlooked, but often seen. That's object packaging.

Consider the question: why can a number be a primitive type but can use the toString method? Only objects have methods, so why can numbers be used?

Let x = 1x.toString () / / "1"

Because when x needs to use a method, JavaScript temporarily converts it to an object by calling new Number (x), which inherits the method of the Number object, so you can call toString. Similarly, there are strings, Boolean values, which are also converted through various constructors. That's why undefined and null can't use toString because they don't have constructors.

X = nullx.toString () / / VM289:1 Uncaught TypeError: Cannot read property 'toString' of / / null// at: 1Rank 3max / (anonymous) @ VM289:1x = undefinedx.toString () / / VM305:1 Uncaught TypeError: Cannot read property' toString' of / / undefined// at: 1:3

So far, that's all I know about automatic conversion. I'll add it later. So what are the rules in the process of automatic conversion?

Automatic conversion rules any-> boolean

When other types of values are converted to boolean, only these are converted to false, and the others are true: undefined, null, ", 0,-0, NaN.

Boolean (0) / / falseBoolean (") / / falseBoolean (NaN) / / falseBoolean (undefined) / / falseBoolean (null) / / false// empty array empty function trueBoolean ({}) / / trueBoolean ([]) / / trueBoolean (function () {}) / / true// is a boolean object at this time, not the original value, so it is trueBoolean (new Boolean (false)) / / trueany-> number

When other types of values are converted to number, it is more complicated:

1.boolean-> number

True-> 1

False-> 0

2.string-> number

A string made up of numbers can be converted directly to numbers, and the spaces at the beginning and end can be ignored. Strings that do not match will return NaN.

+'/ / 0 empty string + '100' / / 100 ignore spaces +' 100aa' / / NaN has other non-digits

Note: the rule here is the rule of automatic conversion. If the transformation is displayed, the constructor Number () is the same as this rule, while the parsing rule of window.parseInt () window.parseFloat is different. As follows

Window.parseInt ('100a') / / 100window.parseFloat ('100.11a') / / 100.11

3. Object-> number

Object will first attempt to call valueOf to return the original value, if not, call toString to return the original value, and then convert it. Look at a few examples.

+ new Date () / / 1529483712712 the valueOf of the date object returns the number of millimeters, that is, the number + [] / / 0 array valueOf for itself, and then call toString to return "". The empty string is converted to a number of 0 + ['1'] / / 1. Similarly, toString returns "1", and converts it to a number of "1 + ['1'] / / NaN toString returns" 1 ". 2 "converted to digital NaN+ {} / / NaN toString [Object,Object], converted to digital NaN

4.undefined null

Null-> 0

Undefined-> NaN

Any-> string

1.null undefined boolean number

The conversion of these primitive types is as simple as wrapping themselves in quotation marks.

'+ 1 / / "1"' + true / / "true"''+ undefined / / "undefined"''+ null / / "null"

2.object-> string

It's similar to converting an object to a number, except that you call toString first and then valueOf.

'' + {} / / "[object Object]"''+ [] / "/"'+ [1meme 2mai3] / / "1meme 2Yue3" + function () {} / / "function () {}"'+ new Date () / / "Wed Jun 20 2018 16:50:56 GMT+0800 (China Standard time)"

You can see that different objects are quite different. The array will separate each element with a comma to generate a string. Date object toString returns Chinese standard time. From here, you can see the different logic of converting and converting into numbers. Try toString before valueOf.

Thank you for reading this article carefully. I hope the article "when will the automatic conversion of JavaScript occur" shared by the editor will be helpful to everyone? at the same time, I also hope that you will support and pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

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