自学内容网 自学内容网

JavaScript code puzzle: convert a Boolean to Number

Write a function fn that receives a Boolean and returns it's representation as a Number. So true becomes 1 and false becomes 0.

Contstraints:

  • no Number constructor or any of it's prototype allowed
  • no Math functions allowed
  • no toNumber implementations allowed either
  • Strings of numbers, such as '1' and '0' do not count
  • Assume the function always receives a valid boolean (so no null or undefined or other types need to be considered).

Tests:

 console.assert(fn(true) === 1)
 console.assert(fn(false) === 0)

Note:

It's marked as #beginners, because it's solution easier than you might think.

Bonus:

It's possible to solve it with 9 characters overall.


原文地址:https://blog.csdn.net/w2sft/article/details/140242185

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!