JavaScript Jsquirks: 列出那些变态的 JS 类型转换

suffering · 发布于 2014年8月08日 · 最后由 suffering 回复于 2014年8月08日 · 1069 次阅读
709

最近从基础开始学习JS, 被其中的动态类型转换弄得受不了了, 于是写了Jsquirks (好吧, 我承认是我在参加Elance的JS Skill Test时被里面的题玩了, 于是我才决定重基础开始研究JS的.) 研究JS的动态类型转换时, 总是试图去找其中的模式, 结果往往自以为发现了一个能用规则, 结果一眨眼就会蹦出个反例. 于是就写了段代码用穷举的方式列出各种变态的特殊值与各种值的可能组合, 同时列出其值. 后来干脆做成了网页版的, 可自由选择用于组合的operandoperator. github发布, 而后上线. 与大家分享. 对JS有兴趣的同学可以去逛逛. 各种希奇古怪的计算结果啊, 我表示再也不会试图去总结什么固定模式了.

好吧, 贴上才写的README.md:

Javascript Quirks with special values and Operations

Demo online: http://jsquirks.zhuboliu.me

Do What

The App combinate the special values and values you selected to simple expressions, run it with the function eval, and display the list of outputs in a table and logged it in the console. By using this, you can find some weired pattern in javascript value type converting.

Special Values

var special_values       = [NaN, null, undefined, 0, 1, 2, true, false, Infinity, -Infinity, " ", "a"];

Operators

var arithmatic_operators = ["+", "-", "*", "/", '%'];
var comparison_operators = [">", ">=", "<", "<="];
var logical_operators    = ["&&", "||"];
var equality_operators   = ["==", "!=", "===", "!=="];
var bitwise_operators    = ["<<", "<<<", ">>", ">>>"];
var unary_operators      = ['typeof', 'void', '+', '-', '~', '!', '!!'];
var operators = {
  arithmatic: arithmatic_operators,
  comparison: comparison_operators,
  logical: logical_operators,
  equality: equality_operators
}

You can add some other operations such as bitwise operaters to the list.

Why am I doing this?

As you know, Javascript will dynamically convert value type in different situations;

The type converting is very weird. I tried to find the inner-rule of dynamic type converting, but I found nothing, It seems that there is no hard and fast rule at all. Every time I found a rule in one place, I found it was wrong in another place later.

At last, I write this simple tool to help me find the rules, of cause it's useless. But with this tool I found some quirks I never found before. Hope this will help.

If You are preparing for some javascript quiz ,for example Elance skill test, this may help. If you found something wrong in the output, please send me a email or open an issue. If you found some hard and fast rule, please pull request.

Resources

TODO

  • add some resourses helpful for understanding the value type converting.
  • add bitwise operators
  • add new to operators
共收到 2 条回复
1553

弓虽!可以当手册用了

709

#1楼 @Peter , 原本就是设计成console版的手册的. 用排列组合的方式列出所有的可能的组合. 但是一运行就是800余行的结果, 实在不好用. 于是就写了个网页版的.

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册