JavaScript implicit type conversion _javascript tips

Source: Internet
Author: User
Tags arithmetic arithmetic operators

The data type of JavaScript is very weak (otherwise it will not be called a weak-type language)! When using arithmetic operators, the data types on either side of the operator can be arbitrary, for example, a string can be added to a number. The difference between data types can be performed because the JavaScript engine silently converts them implicitly before the operation, as follows the addition of numeric types and Boolean types:

Copy Code code as follows:

3 + true; 4

The result is a numerical type! If it is in the C or Java environment, the above operation will certainly be due to the operator on both sides of the data type inconsistency caused the error! However, in JavaScript there are only a few cases where the error type causes an error, such as calling a non function, or reading a null or undefined property, as follows:

Copy Code code as follows:

"Hello" (1); Error:not a function
null.x; Error:cannot Read Property ' x ' of NULL

In most cases, JavaScript does not go wrong, but it automatically makes the appropriate type conversions. For example-, *,/, and% arithmetic operators convert the operands to numbers, but the "+" number is somewhat different, in some cases it is an arithmetic plus, in some cases a string concatenation symbol, depending on the operand, as follows:

Copy Code code as follows:

2 + 3; 5
"Hello" + "world"; "Hello World"

But what happens if strings and numbers are added together? JavaScript automatically converts numbers to characters, regardless of whether the number is in front or before the string, as follows:

Copy Code code as follows:

"2" + 3; "23"
2 + "3"; "23"

String and number addition result is string, string and number addition result is string, string and number add result is string, important thing say three times!!!!!!

Also, note that the operation direction of "+" is left to right, as follows:

Copy Code code as follows:

1 + 2 + "3"; "33"

This is equivalent to the following:

Copy Code code as follows:

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

In contrast, the following results are not the same:

Copy Code code as follows:

1 + "2" + 3; "123"

However, implicit type conversions sometimes hide errors, such as null converting to 0,undefined 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 code as follows:

var x = NaN;
x = = NaN; False

Although JavaScript provides isnan to detect whether a value is Nan, this is also not very precise because, before calling the isNaN function, there is an implicit conversion process, which converts values that are not nan to Nan, as follows:

Copy Code code as follows:

isNaN ("foo"); True
isNaN (undefined); True
isNaN ({}); True
isNaN ({valueof: "foo"}); True

The code above, we use isNaN to test, after discovering strings, undefined, even objects, the results are returned to TRUE!!! But we can't always say that they are Nan, right? In a nutshell, the conclusion is that isNaN detection of NAN is unreliable!!!

Fortunately, there is a reliable and accurate way to detect Nan. We all know that only Nan is not equal to himself, then we have to use the unequal number (!). = =) 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 pattern as a function, as follows:

function Isreallynan (x) {return
x!== x;
}

Ok,nan detection method is so simple, we continue to discuss the implicit conversion of objects!

An object can be converted to a raw value, and the most common method is to convert it to a string, as follows:

"The Math object:" + math; "The Math object: [Object Math]"
"The JSON object:" + json; "The JSON object: [Object JSON]"

object to a string is called his tosting function, you can manually call it to detect:

Math.tostring (); "[Object Math]"
json.tostring ();//[Object JSON]

Similarly, objects can also be converted into numbers, he is 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"

In most cases, however, this is not what we want, generally, to make the same values as valueof and ToString (although the types can be different).

The last type of coercion that we often call "truth operations", such as, if, | |, &&, is that their operands are not necessarily Boolean amounts. JavaScript converts values of a non-Boolean type to a Boolean by using simple conversion rules. Most of the values are converted to true, and only a few are false, and they are: false, 0,-0, "", NaN, null, undefined, because there are numbers and strings and the value of the object is false, so It is not unsafe to judge the parameters of a function directly using the truth conversion. For example, there is a function that can have a default worthy optional parameter, as follows:

function point (x, y) {
if (!x) {
x = up to;
}
if (!y) {
y =;
return {x:x, y:y};
}

This function ignores any values that are false, including 0,-0;

Copy Code code 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 = on-the
;
if (typeof y = = = "undefined") {
y =
;
return {x:x, y:y};
}

This type of writing can be distinguished by opening 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) {...}

Summarize:

1. Type errors may be hidden by type conversions.

2. "+" can represent both a string connection and an arithmetic addition, depending on its operands, if one is a string, then the string is concatenated.

3. The object converts itself to a number through the valueof method, converting itself into a string through the ToString method.

4. An object with a valueof method should define a corresponding tostring method that returns the string form of an equal number.

5. When detecting some undefined variables, you should use TypeOf or compare them with undefined, rather than using the truth arithmetic directly.

About JavaScript implicit type conversion for everyone to introduce here, I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.