动态执行javascript代码,用eval或Function,哪个性能好呢?
请参考下面这个例子吧。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>动态执行javascript代码_www.jb200.com</title> <script type="text/javascript"> /** * 动态执行javascript代码 * author www2 */ String.prototype.code = function(){ return (new Function('with(this) { return ' + this + '}' )).call({}); }; var sCode = 'Math.round(3+2.5)*1.2'; var result = 0; for(var i=0;i<10000;i++){ result += sCode.code(); //result += eval(sCode); } alert(result); </script> </head> <body> </body> </html>