JavaScript’s data types are very weak (otherwise it wouldn’t be called a weakly typed language)! 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
The result is a numeric value! If it is in a C or Java environment, the above operation will definitely 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 when calling a non-function, or reading a null or undefined property, as follows:
"hello"(1); // error: not a function
null.x; // error: cannot read property 'x' of null
In most cases, JavaScript will not make errors, but will automatically perform the corresponding type conversion. For example, arithmetic operators such as -, *, /, and % will convert their 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. The connection symbol depends on its operands, as follows:
2 + 3; // 5
"hello" + " world"; // "hello world"
But what would be the result if strings and numbers were added? JavaScript will automatically convert numbers into characters, regardless of whether the number or string comes first, as follows:
"2" + 3; // "23"
2 + "3"; // "23"
The result of adding a string and a number is a string. The result of adding a string and a number is a string. The result of adding a string and a number is a string. Say important things three times! ! ! ! ! !
In addition, it should be noted that the operation direction of "+" is from left to right, as follows:
1 + 2 + "3"; // "33"
This is equivalent to:
(1 + 2) + "3"; // "33"
In contrast, the following results are different:
1 + "2" + 3; // "123"
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
Although JavaScript provides isNaN to detect whether a certain value is NaN, this is not very accurate because there is an implicit conversion process before calling the isNaN function, which will convert those Values that are not originally NaN are converted to NaN, as follows:
isNaN("foo"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN({ valueOf: "foo" }); // true
After testing the above code using isNaN, we found that strings, undefined, and even objects all returned true! ! ! However, we can't say that they are also NaN, right? All in all, the conclusion is: isNaN detection of NaN is not reliable! ! !
Fortunately, there is a reliable and accurate way to detect NaN. We all know that NaN is the only one that does not equal itself. Then, we can use the inequality sign (!==) to determine whether a number is equal to itself, so that 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
We can also define this mode as a function, as follows:
function isReallyNaN(x) { return x !== x; }
OK, the NaN detection method is that simple. Let’s continue to discuss the 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]"
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]"
Similarly, objects can also be converted into numbers through the valueOf function. Of course, you can also customize this valueOf function, as follows:
"J" + { toString: function() { return "S"; } }; // "JS" 2 * { valueOf: function() { return 3; } }; // 6
If an object has both the valueOf method and the toString method, then the valueOf method will always be called first, as follows:
var obj = { toString: function() { return "[object MyObject]"; }, valueOf: function() { return 17; } }; "object: " + obj; // "object: 17"
However, in most cases, this is not what we want. In general, try to make the values represented by valueOf 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 with false values, so, It is not very safe to directly use truth 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 }; }
This function will ignore any parameter whose true value is false, including 0, -0;
point(0, 0); // { x: 320, y: 240 }
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 }; }
This way of writing can distinguish between 0 and undefined:
point(); // { x: 320, y: 240 } point(0, 0); // { x: 0, y: 0 }
Another method is to use parameters to compare with undefined, as follows:
if (x === undefined) { ... }
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 them is a string, then it is string concatenation.
3. The object converts itself into a number through the valueOf method, and converts itself into a string through the toString method.
4. Objects with valueOf methods should define a corresponding toString method to return equal numbers in string form.
5. When detecting some undefined variables, typeOf or comparison with undefined should be used instead of true value operation directly.
That’s it for everyone about JavaScript implicit type conversion. I hope it will be helpful to you!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was


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

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

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
