也许一般代码不会触及最大参数长度和最大栈深度,但某些特殊场合,检测这两个参数还是有必要的
例如:用递归计算斐波那契数列的第n个值,不了解最大栈深度,难免显得肤浅
又例如:将一串charCode转成String,不了解最大参数长度,采用字符串拼接的方式,效率提不上,特别是在串较长的情况下
function getMaximumSupportedArgumentsLength(){ var args={length:0}; function noop(){} function test(n){ args.length=n; try{noop.apply(null,args);}catch(e){return false;} return true; } function getNum(min,max){ var start=min, end=max, mid=Math.ceil((start+end)/2), count=0; while(start<end){ if(test(mid)){ start=mid; mid=Math.floor((start+end)/2); }else{ end=mid-1; mid=Math.floor((start+end)/2); } count++; if(count>32){return max;} } return mid; } return getNum(0x7f,0x7fffffff); } function getMaximumCallStackSize(){ var size=0; function test(){ size++; test(); } try{ test(); }catch(e){ return size; } } //Maximum Supported Arguments Length //CH34 124782 //FF29 500000 //SF7 65536 //Maximum Call Stack Size //CH34 20926 in <script>, 20804 in console //FF29 21###(varies) in <script>, 49993 in console //SF7 43517 in <script>, 43509 in console