简体   繁体   中英

Why is Math.sign([]) = 0, Math.sign([20]) = 1, and Math.sign([20, 30, 40]) = NaN?

As Math.sign() accepts a number parameter or number as a string as per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign , why does it give the following results and how are the internal conversions taking place while giving these results?

 console.log(Math.sign([])); // 0 console.log(Math.sign([20])); // 1 console.log(Math.sign([20, 30, 40])) // NaN

It expects to be passed a number. If a non-primitive is passed to it, it attempts to convert that non-primitive to a number first.

When arrays are converted to numbers, their values are first joined by , to create a string, and then the interpreter tries to turn that string into a number. So with

Math.sign([]);

the empty array is converted to the empty string, which is then turned into a number - and Number('') is 0, hence the result is 0.

With [20] , this is joined into a string of '20' , which is then turned into the number 20 , whose sign is positive.

With [20, 30, 40] , this is joined into '20,30,40' , which cannot be turned into a number:

 console.log(Number('20,30,40'));

So the output is NaN .

Best to always do explicit type casting when you aren't 100% sure of what the result of implicit type coercion will be.

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