Table of Contents
Implicit conversion of objects
Home Web Front-end JS Tutorial What is implicit type conversion? Introduction to js implicit type conversion

What is implicit type conversion? Introduction to js implicit type conversion

Aug 11, 2018 pm 04:32 PM
implicit type conversion

This article brings you what is implicit type conversion? The introduction to js implicit type conversion has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

JavaScript's data types are very weak. When using arithmetic operators, the data types on both sides of the operator can be arbitrary. For example, a string can be added to a number. The reason why operations can be performed between different data types is because the JavaScript engine will quietly perform implicit type conversion on them before the operation. The following is the addition of numeric types and Boolean types:

3 + true; 
// 结果:4
Copy after login

The result is a numeric value! If it is in a C or Java environment, the above operation will cause an error because the data types on both sides of the operator are inconsistent. However, in JavaScript, only in a few cases, the wrong type will cause an error, such as calling a non-function, or reading When taking null or undefined attributes, it is as follows:

"hello"(1); 
//结果: error: not a function
null.x; 
// 结果:error: cannot read property 'x' of null
Copy after login

In most cases, JavaScript will not make an error, but will automatically perform the corresponding type conversion. For example, arithmetic operators such as -, *, /, and % will convert the operands into numbers, but the " " sign is a little different. In some cases, it is an arithmetic plus sign, and in other cases, it is a string concatenation. Symbol, the specific details depend on its operands, as follows:

2 + 3; 
//结果: 5
"hello" + " world"; 
// 结果:"hello world"
Copy after login

However, if strings and numbers are added, JavaScript will automatically convert the numbers into characters, regardless of whether the numbers or strings come first. As follows:

"2" + 3; 
// 结果:"23"
2 + "3";
 //结果: "23"
Copy after login

The result of adding a string and a number is a string!

It should be noted that the operation direction of " " is from left to right, as follows:

1 + 2 + "3"; 
// "33"
Copy after login

This is equivalent to the following:

(1 + 2) + "3"; 
// "33"
Copy after login

Compare Next, the following results are different:

1 + "2" + 3; 
// "123"
Copy after login

However, implicit type conversion sometimes hides some errors, for example, null will be converted to 0, and undefined will be converted to NaN. It should be noted that NaN and NaN are not equal (this is due to the precision of floating point numbers), as follows:

var x = NaN;
x === NaN; // false
Copy after login

Although JavaScript provides isNaN to detect whether a value is NaN, however, This is not very accurate, because before calling the isNaN function, there is an implicit conversion process, which will convert values ​​that are not NaN to NaN, as follows:

isNaN("foo"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN({ valueOf: "foo" }); // true
Copy after login

The above code , after we used isNaN to test, we found that strings, undefined, and even objects all returned true! ! ! But they are not NaN.

In short: isNaN detection of NaN is not reliable! ! !

There is a reliable and accurate way to detect NaN.

We all know that only NaN is not equal to itself. You can use the inequality sign (!==) to determine whether a number is equal to itself. Therefore, NaN can be detected, as follows:

var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
Copy after login

We can also define this mode as a function, as follows:

function isReallyNaN(x) {
    return x !== x;
}
Copy after login

Implicit conversion of objects

Objects can be converted into primitive values , the most common method is to convert it into a string, as follows:

"the Math object: " + Math; // "the Math object: [object Math]"
"the JSON object: " + JSON; // "the JSON object: [object JSON]"
Copy after login

The object is converted into a string by calling its toSting function. You can call it manually to check:

Math.toString(); // "[object Math]"
JSON.toString(); // "[object JSON]"
Copy after login

Similarly, objects can also be converted into numbers through the value Of function. Of course, you can also customize the value Of function, as follows:

"J" + { toString: function() { return "S"; } }; // "JS"
2 * { valueOf: function() { return 3; } }; // 6
Copy after login

If an object also exists valueOf method and toString method, then the value Of method will always be called first, as follows:

var obj = {
    toString: function() {
        return "[object MyObject]";
    },
    valueOf: function() {
        return 17;
    }
};
"object: " + obj; // "object: 17"
Copy after login

Generally, try to make the values ​​represented by value Of and toString the same (although the types can be different).

The last type of forced type conversion is often called "truth operation", such as if, ||, &&, their operands are not necessarily Boolean. JavaScript will convert some non-Boolean values ​​into Boolean values ​​through simple conversion rules. Most values ​​will be converted to true, only a few are false, they are : false, 0, -0, "", NaN, null, undefined, because there are numbers, strings and objects The value is false, so it is not very safe to directly use true value conversion to determine whether the parameters of a function are passed in. For example, there is a function that can have optional parameters with default values, as follows:

function point(x, y) {
if (!x) {
    x = 320;
}
if (!y) {
    y = 240;
}
    return { x: x, y: y };
}
Copy after login

This function will ignore any parameters whose true value is false, including 0, -0;

point(0, 0); // { x: 320, y: 240 }
Copy after login

A more accurate way to detect undefined is to use the typeof operation:

function point(x, y) {
if (typeof x === "undefined") {
    x = 320;
}
if (typeof y === "undefined") {
    y = 240;
}
    return { x: x, y: y };
}
Copy after login

This way of writing can distinguish between 0 and undefined:

point(); // { x: 320, y: 240 }
point(0, 0); // { x: 0, y: 0 }
Copy after login

Another method is to use parameters to compare with undefined. As follows:

if (x === undefined) { ... }
Copy after login

Summary:

1. Type errors may be hidden by type conversion.

2. " " can represent both string concatenation and arithmetic addition, depending on its operands. If one of the operands is a string, then it is string concatenation.

3. The object converts itself into a number through the value Of method, and converts itself into a string through the toString method.

4. Objects with value Of methods should define a corresponding toString method to return equal numbers in string form.

5. When detecting some undefined variables, type Of or comparison with undefined should be used instead of true value operation directly.

Related recommendations:

JS implicit type conversion summary

How to use implicit conversion? Summarize the usage of implicit conversion examples

A brief introduction to implicit type conversion of JavaScript data types_javascript skills

The above is the detailed content of What is implicit type conversion? Introduction to js implicit type conversion. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are implicit type conversions and explicit type conversions in C language? What are implicit type conversions and explicit type conversions in C language? Sep 08, 2023 pm 10:13 PM

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

What implicit type conversions exist in mysql? What implicit type conversions exist in mysql? Nov 14, 2023 am 11:28 AM

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.

Type conversion of golang function Type conversion of golang function Apr 19, 2024 pm 05:33 PM

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.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

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.

Implicit type conversion: An exploration of different variations of types and their applications in programming Implicit type conversion: An exploration of different variations of types and their applications in programming Jan 13, 2024 pm 02:54 PM

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,

Several situations of mysql index failure Several situations of mysql index failure Feb 21, 2024 pm 04:23 PM

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.

What is the difference between int and float in c language What is the difference between int and float in c language Apr 29, 2024 pm 10:12 PM

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.

What is the relationship between c# and c language? What is the relationship between c# and c language? Apr 04, 2024 pm 12:03 PM

There are close relationships between the C# and C languages, including syntax similarities, object-oriented programming support, garbage collection, type safety, and platform differences. C# inherits the syntax and object-oriented programming foundation of the C language and extends it to include features such as garbage collection, type safety, and platform specificity.

See all articles