To explore the pitfalls of JS type conversion.

Source: Internet
Author: User
For example, many books teach us the priority. "You don't have to recite the priority order. If you're not sure about the priority, just add brackets. "We do this when writing code. But what is the reality? This question will be asked during the interview... I really don't know what this question means... Why do you want to say this?
Just give me an interview question to explain its motivation.
Question:

var bool = new Boolean(false);if (bool) {    alert('true');} else {    alert('false');}

The running result is true !!!
Actually, what is type conversion? Operator priority? These are the most basic.
The rhino book provides a detailed introduction. But I seldom go to the first five chapters of the rhino book...
For example, many books teach us the priority. "You don't have to recite the priority order. If you're not sure about the priority, just add brackets. "
We do this when writing code.
But what is the reality? This question will be asked during the interview...
I really don't know what this question means...
This article tries to solve the type conversion problem so far, and tries to back the 49-page table in the JS authoritative guide.
What are false values?
6 in total:

0 or + 0,-0, NaN "" falseundefinednull

The above sequence is arranged according to the basic type.
None of the above !! Even in the following format:

Infinity '0', 'false', "" (space character) Any reference type: [], {}, function (){}

The correct understanding of if (a & B) is as follows:A & B evaluates the expression and converts it to the Boolean type.
& Is a short-circuit syntax. After the value is evaluated, it is not necessarily a Boolean type, not to convert the Boolean values on both sides before the operation.
For example, the result of 2 & 3 is 3, not true.
Therefore, if (a & B) is an incorrect description of "if a and B are both true.
Convert other basic types to strings, Basically as expected:

console.log("" + null);      // "null"console.log("" + undefined); // "undefined"console.log("" + false);     // "false"console.log("" + true);      // "true"console.log("" + 0);         // "0"console.log("" + NaN);       // "NaN"console.log("" + Infinity);  // "Infinity"

Convert other basic types to numbers, Requires special memory:

console.log(+null);          // 0console.log(+undefined);     // NaNconsole.log(+false);         // 0console.log(+true);          // 1console.log(+"");            // 0console.log(+'1');           // 1console.log(+'1x');          // NaN

Null indicates that the null character is 0, and undefined indicates NaN.
Above, the basic type conversion is described as white.

Next let's take a look at converting the reference type to the basic type.
Convert the reference type to boolean, always true
Convert the reference type to a string

1. Call the toString method first (if any) to check whether the returned result is of the original type. If yes, convert it to a string and return it. 2. Otherwise, call the valueOf method (if any) to check whether the returned result is of the original type. If yes, convert it to a string and return it. 3. Other errors.

Convert the reference type to a number

1. Call the valueOf method first (if any) to check whether the returned result is of the basic type. If yes, convert it to a number and return it. 2. Otherwise, call the toString method (if any) to check whether the returned result is of the basic type. If yes, convert it to a number and return it. 3. Other errors.

First, let's take a look at what common reference types toString and valueOf return?

Var a ={}; console. dir (. toString (); // "[object Object]" console. dir (. valueOf (); // var B = [1, 2, 3]; console. dir (B. toString (); // "1, 2, 3" console. dir (B. valueOf (); // var c = [[1], [2]; console. dir (c. toString (); // "1, 2" console. dir (c. valueOf (); // var d = function () {return 2}; console. dir (d. toString (); // "function () {return 2}" console. dir (d. valueOf (); // the object itself

Therefore, the conversion to strings and numbers is as follows:

var a = {};console.dir(a + "");         // "[object Object]"console.dir(+a);             // NaN var b = [1, 2, 3];console.dir(b + "");         // "1,2,3"console.dir(+b);             // NaN var c = [[1],[2]];console.dir(c + "");         // "1,2"console.dir(+c);             // NaN var d = function() {return 2};console.dir(d + "");         // "function () {return 2}"console.dir(+d);             // NaN

Another error is reported:

Var a = {};. toString = function () {return {};} console. log ("" + a); // error console. log (+ a) // Error

The above type conversion rules are basically complete.

Finally, let's look at the "="
The interview questions are as follows:

var a = false;var b = undefined;if (a == b) {    alert('true');} else {    alert('false');}

This indicates that true is displayed. That day! Why is it false?
Haha...
The double equal sign. If the two types are different, implicit conversion occurs. The 75 pages of the rhino book are summarized as follows:

1. null and undefined are equal. 2. convert a number to a number and compare it with a string. 3. If there is true or false, convert it to 1 or 0 and then compare it. 4. If there is a reference type, valueOf is first called. 5. The rest are not equal.

Therefore:

console.log(undefined == false); // falseconsole.log(null == false);      // falseconsole.log(0 == false);         // trueconsole.log(NaN == false);       // falseconsole.log("" == false);        // true

0 = false is true based on 3rd.
"" = False is true according to 3rd, it is changed to "" = 0, and then according to 2nd.
Example 1:

console.log([[2]] == 2)

The result is true for the following reasons:
[[2] valueOf is the object itself, not the basic type.
The result of trying to call toString is '2 '.
Therefore, it becomes a comparison between '2' and number 2. According to 2nd, equal. WTF !!
The last sentence is "=.
This article is complete.

Related Article

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.