


A brief introduction to implicit type conversion of JavaScript data types_javascript skills
JavaScript data types are divided into six types, namely null, undefined, boolean, string, number, and object. object is a reference type, and the other five are basic types or primitive types. We can use the typeof method to print out which type something belongs to. To compare variables of different types, you must first convert the type, which is called type conversion. Type conversion is also called implicit conversion. Implicit conversions usually occur with the operators addition, subtraction, multiplication, division, equals, and less than, greater than, etc. .
typeof '11' //string typeof(11) //number '11' < 4 //false
This chapter separately introduces implicit data type conversion in JavaScript. A good grasp of it can simplify many operations in practical applications.
See the following code example:
var arr = [5]; console.log(arr+"");
The above code is an operation to implicitly convert an array into a string. Isn’t it much simpler than the following method:
var arr = [5]; console.log(arr.toString());
Implicit data type conversions like the above are widely used in actual coding. Let’s get to the point.
1. Data type conversion between value types:
For data types in JavaScript, please refer to the chapter "Detailed explanation of JavaScript data types".
(1). Numbers and strings use the + operator:
If you use the + operator to operate numbers and strings, the numbers will be converted to strings first, and then string concatenation operations will be performed:
var antzone = "antzone"; var num = 8; console.log(antzone+num);
(2). + operator operation involving Boolean values:
If there is a Boolean type involved, the Boolean value will first be converted into the corresponding number or string, and then the corresponding string connection or arithmetic operation will be performed.
var bool = true; var num = 8; console.log(bool + num);
The above code first converts true to the number 1, and then performs arithmetic addition.
var bool = true; var num = "8"; console.log(bool + num);
The above Boolean value will be converted into the corresponding string form "true", and then string concatenation is performed.
(3). Subtraction operation:
If a subtraction operation is performed, both operands will be converted to numbers first, and then the arithmetic operation will be performed:
var bool = true; var num = "8"; console.log(bool - num);
true will be converted to the number 1, the string "8" will be converted to the number 8, and then arithmetic operations will be performed.
The same applies to the conversions of multiplication, division, greater than, less than and subtraction, so I won’t give examples anymore.
(4).==Equality operation:
undefined and null are special. They both use the == operator to return true.
console.log(undefined==null);
When comparing other value types, the operands will be converted into numbers
console.log("3"==3);
The above code will convert the string "3" into a number and then compare it.
console.log("1"==true);
The above code will convert "1" and true into numbers respectively, and then compare them.
2. Convert reference type to value type:
Converting reference types (objects) to value types is much more complicated. The distribution is introduced below.
The two methods of object inheritance can help us realize the conversion function from object to value type:
(1).toString() method.
(2).valueOf() method.
Normally, we think that to convert an object into a string, you need to call the toString() method, and to convert an object into a number, you need to call the valueOf() method, but it is not that simple when it is actually applied. See the following code example:
var obj = { webName: "脚本之家", url:"softwhy.com" } console.log(obj.toString());
As can be seen from the above code, the toString() method does not convert the object into a string that reflects this object.
var arr = [1, 2, 3]; console.log(arr.valueOf());
As can be seen from the above code, the valueOf() method does not convert the object into a number that reflects this object.
var arr = [1, 2, 3]; console.log(arr.toString());
数组对象的toString()方法能够将数组转换为能够反映此数组对象的字符串。
总结如下:
(1).有些对象只是简单继承了toString()或者valueOf()方法,比如第一个例子。
(2).有些对象则不但是继承了两个方法,而且还进行了重写。
所以有些对象的方法能够达成转换成字符串或者数字的目标,有些则不能。
调用toString()或者valueOf()将对象转换成字符串或者数字的规则如下:
调用toString()时,如果对象具有这个方法,则调用此方法;如果此方法返回一个值类型数据,那么就返回这个值类型数据,然后再根据所处的上下文环境进行相关数据类型转换。如果没有toString(),或者此方法返回值并不是一个值类型数据,那么就会调用valueOf()(如果此方法存在的话),如果valueOf()返回一个值类型数据,那么再根据所处的上下文环境进行相关的数据类型转换。
进一步说明:
(1).上面介绍了通常默认情况下valueOf()和toString()方法的作用(将对象转换为数字或者字符串),但是需要注意的是,这并不是硬性规定,也就是说并不是valueOf()方法必须要返回数字或者toString()方法必须要转换为字符串,比如简单继承的这两个方法就无法进行实现转换为数字和字符串的功能,再比如,我们可以自己称谢这两个方法,返回值也没有必要是数字或者字符串。
(2).还有需要特别注意的一点就是,很多朋友认为,转换为字符串首先要调用toString()方法, 其实这是错误的认识,我们应该这么理解,调用toString()方法可以转换为字符串,但不一定转换字符串就是首先调用toString()方法。
看如下代码实例:
var arr = []; arr.valueOf = function () { return "1"; } arr.toString = function () { return "2"; } console.log(arr + "1");
上面的代码中,arr是要被转换为字符串的,但是很明显是调用的valueOf()方法,而没有调用toString()方法。有些朋友可能会有这样的质疑,难道[2]这样的数字转换成字符串"2",不是调用的toString()方法吗。
代码如下:
var arr = [2]; console.log(arr + "1");
其实过程是这样的,首先arr会首先调用valueOf()方法,但是数字的此方法是简单继承而来,并没有重写(当然这个重写不是我们实现),返回值是数组对象本身,并不是一个值类型,所以就转而调用toString()方法,于是就实现了转换为字符串的目的。
总结如下:
大多数对象隐式转换为值类型都是首先尝试调用valueOf()方法。但是Date对象是个例外,此对象的valueOf()和toString()方法都经过精心重写,默认是调用toString()方法,比如使用+运算符,如果在其他算数运算环境中,则会转而调用valueOf()方法。
代码实例如下:
var date = new Date(); console.log(date + "1"); console.log(date + 1); console.log(date - 1); console.log(date * 1);
以上内容是小编给大家介绍的JavaScript数据类型之隐式类型转换的全部内容,希望大家喜欢。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The implicit type conversions that exist in MySQL include string to numeric types, date and time types, floating point and integer types, NULL values, etc. Detailed introduction: 1. Implicit type conversion from string to numeric type. When a string is compared or calculated with a value of numeric type, MySQL will convert the string into numeric type; 2. Implicit type conversion of date and time types. Implicit type conversion, in MySQL, date and time types can also perform implicit type conversion with other data types; 3. Implicit type conversion of floating point and integer types, etc.

Converting one data type to another is called type conversion. Implicit Type Conversion Explicit Type Conversion Implicit Type Conversion The compiler provides implicit type conversion when the operands have different data types. It is done automatically by the compiler by converting smaller data types to larger data types. inti,x;floatf;doubled;longintl;Here, the above expression finally evaluates to a "double" value. Example The following is an example of implicit type conversion-intx;for(x=97;x<=122;x++){ printf("%c",x);/*Im

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

In-function type conversion allows data of one type to be converted to another type, thereby extending the functionality of the function. Use syntax: type_name:=variable.(type). For example, you can use the strconv.Atoi function to convert a string to a number and handle errors if the conversion fails.

Explore the different types of implicit type conversions and their role in programming Introduction: In programming, we often need to deal with different types of data. Sometimes, we need to convert one data type to another type in order to perform a specific operation or meet specific requirements. In this process, implicit type conversion is a very important concept. Implicit type conversion refers to the process in which the programming language automatically performs data type conversion without explicitly specifying the conversion type. This article will explore the different types of implicit type conversions and their role in programming,

The Go language uses static typing and performs type checking at compile time to avoid runtime type errors. Basic types include integers, floats, booleans, strings, and byte slices. Composite types include arrays, slices, structures, interfaces, and channels. Go language supports type inference and various type conversion operators. Type aliases facilitate code readability and maintainability. Static typing brings security, performance, and maintainability advantages.

Common situations: 1. Use functions or operations; 2. Implicit type conversion; 3. Use not equal to (!= or <>); 4. Use the LIKE operator and start with a wildcard; 5. OR conditions; 6. NULL Value; 7. Low index selectivity; 8. Leftmost prefix principle of composite index; 9. Optimizer decision; 10. FORCE INDEX and IGNORE INDEX.

The difference between int and float variables in C language is that they have different types: int is used to store integers, while float is used to store decimals. Storage size: int usually takes 4 bytes, and float also takes 4 bytes. Precision: int represents an exact integer, while float has limited precision. Range: int typically ranges from -2^31 to 2^31-1, while float has a wider range. Arithmetic operations: int and float can perform arithmetic operations and comparisons, but the results may be affected by precision limitations. Type conversion: Explicit or implicit type conversion can be performed between int and float.
