Home > Web Front-end > JS Tutorial > body text

JavaScript implicit type conversion_javascript tips

WBOY
Release: 2016-05-16 15:10:40
Original
1182 people have browsed it

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:

Copy code The code is as follows:

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:

Copy code The code is 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:

Copy code The code is 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:

Copy code The code is 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:

Copy code The code is as follows:

1 + 2 + "3"; // "33"

This is equivalent to:

Copy code The code is as follows:

(1 + 2) + "3"; // "33"

In contrast, the following results are different:

Copy code The code is as follows:

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:

Copy code The code is 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:

Copy code The code is 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
Copy after login

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

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

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]"
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 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
Copy after login

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"
Copy after login

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 };
}
Copy after login

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

Copy code The code is as follows:

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 };
}
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 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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!