简体   繁体   中英

Why does the chrome browser console forcibly coerce a string to a number in javascript?

noob question. I'm learning 'You don't know JS' and I struck this anomaly on page 11:

var a = "42";
var b = Number( a );

console.log( a ); // "42"
console.log( b ); //  42

Now I do get that behaviour if I run it in JS Bin. But in the latest Chrome browser console which I'm learning with, I get this unexpected behaviour:

var a = "42";
var b = Number(a);
console.log(a);
console.log(b);
42              // no quotes?
42
< undefined

And trying manual coercion from a number to a string, also an unexpected result:

a = 42;
b = a.toString();
console.log(a);
console.log(b);
42      
42            // no quotes?
< undefined

Can anyone shed some light on this behaviour please? I have googled it and come up short, cheers.

The fact that the values aren't printed with quotes around them is due to the fact that the string doesn't contain any quotes as its content . So, you shouldn't expect quotes to be produced unless that were the case.

To remove any doubt, you can always check the type with typeof :

 var a = "42"; var b = Number(a); var c = '"String with quotes as part of the content."'; var d = 'String with NO quotes as part of the content.'; console.log(a, typeof a); console.log(b, typeof b); console.log(c, typeof c); console.log(d, typeof d); 

Keep in mind that the way a particular browser decides to implement their console behavior is entirely up to them. There are no standards on this since console is not a part of JavaScript. So, it's entirely normal find differences between one client and another in that regard. What's important is that the JavaScript runtime process the data according to the standard.

When looking at the console you'll notice slight colour difference when logging it out.

A number will be blue whereas a string will be black.

If you don't want unexpected coercions just use === when doing comparisons or do what Scott Marcus suggests .

The Chrome console.log(..) output is always without quotes. Try to see:

console.log("asd")

And try this in the console:

var a = "42";
a;

Should return the wanted result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM