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

Let's discuss the pitfalls of JS type conversion

阿神
Release: 2017-01-23 14:18:04
Original
1173 people have browsed it

Why do you want to say this?
An interview question gives me the motivation for talking about it.
The question is as follows:

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

The running result is true! ! !
Actually, type conversion, operator priority, these things are the most basic.
There is a detailed introduction in the rhinoceros book. But I rarely read the first 5 chapters of the Rhino book. . .
For example, regarding priorities, many books teach us, "There is no need to memorize the priority order. If you are not sure, just add parentheses."
We usually do this when writing code.
But what is the reality? This kind of question will be asked during the interview and you will be asked to answer it. . .
I really don’t know the meaning of this kind of question. . .
The complaints stop here. This article attempts to solve the type conversion problem and try to memorize the table on page 49 of the "JS Authoritative Guide".
What are the false values?
6 in total:

0或+0、-0,NaN
""
false
undefined
null
Copy after login

The above order is arranged according to the basic types.
Nothing else! ! Even if it is in the following form:

Infinity
'0'、'false'、" "(空格字符)
任何引用类型:[],{},function(){}
Copy after login

The correct way to understand if (a && b) is: a && b evaluates the expression and then converts it to the Boolean type.
&& is a short-circuit syntax. After evaluation, it is not necessarily a Boolean type, nor is it converted into Boolean values ​​on both sides and then operated.
For example, the result of 2&&3 is 3, not true.
So if(a && b), what we usually understand, "if a and b are true at the same time", is a wrong way of describing it.
Convert other basic types to strings, which is basically the same 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"
Copy after login

Convert other basic types to numbers, which requires special memory:

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

Where null, the empty character is 0, and undefined is NaN.
Above, the basic type conversions are explained clearly.

Let’s take a look at converting reference types into basic types.
Convert reference type to boolean, always true
Convert reference type to string

1.优先调用toString方法(如果有),看其返回结果是否是原始类型,如果是,转化为字符串,返回。
2.否则,调用valueOf方法(如果有),看其返回结果是否是原始类型,如果是,转化为字符串,返回。
3.其他报错。
Copy after login

Convert reference type to number

1.优先调用valueOf方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。
2.否则,调用toString方法(如果有),看其返回结果是否是基本类型,如果是,转化为数字,返回。
3.其他报错。
Copy after login

First let’s look at what common reference types toString and valueOf return?

var a = {};
console.dir(a.toString());   // "[object Object]"
console.dir(a.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());    // 对象本身
Copy after login

So the corresponding conversion to strings and numbers is:

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

Another error situation:

var a = {};
a.toString = function() {return {};}
console.log("" + a);         // 报错
console.log(+a)              // 报错
Copy after login

The above type conversion rules are basically finished.

Finally, let’s talk about the evil “==”
The interview questions are as follows:

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

I thought true would pop up. Oh my God! Why is it false?
Haha. . .
Double equal sign, if the types of both sides are different, implicit conversion will occur. Rhino book page 75 summarizes it as follows:

1,null和undefined,相等。
2,数字和字符串,转化为数字再比较。
3,如果有true或false,转换为1或0,再比较。
4,如果有引用类型,优先调用valueOf。
5,其余都不相等。
Copy after login

Therefore:

console.log(undefined == false); // false
console.log(null == false);      // false
console.log(0 == false);         // true
console.log(NaN == false);       // false
console.log("" == false);        // true
Copy after login

0 == false The reason why it is true is based on item 3.
The reason why "" == false is true according to Article 3 becomes "" == 0, and then according to Article 2.
Another example from Article 4:

console.log([[2]] == 2)
Copy after login

The above result is true for the following reasons:
[[2]]'s valueOf is the object itself, not the basic type.
The result of trying to call toString is '2'.
So it becomes a comparison of '2' and the number 2. According to Article 2, equal. WTF!!
Finally, using "===" will eliminate these problems.
End of this article.

Related labels:
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!