首页 > 解决方案 > 如何制作一个可以将任何看起来像 javascript 代码的字符串转换为对象的函数?

问题描述

作为javascript新手,我有一个问题。让我们考虑一个看起来像这样的字符串:

 var str = "Math.random() > 0.5";

现在让我们有一些javascript:

  console.log( turnUp( str ) ); // true or false

因此,turnUp()只是我认为可以执行以下操作的函数:

没有turnUp()

 console.log( str );
 // Is equivalent to console.log( "Math.random() > 0.5" );

输出 :

 Math.random() > 0.5

使用turnUp()

 console.log( turnUp( str ) );
 // Is equivalent to console.log( Math.random() > 0.5 );

输出 :

 true

或者

输出 :

 false

因此,借助示例,您可能会了解我的需要!那么,如何制作turnUp()函数呢?

提前致谢

标签: javascriptstringobject

解决方案


eval() 有很多缺点,所以我更喜欢你做这样的事情:

 var turnUp = function(str) {
    return Function(' "use strict"; return (' + str + ') ')();
  }

现在你可以这样做:

 var str = "Math.random() > 0.5";

 console.log( str ); // => Math.random > 0.5
 console.log( turnUp( str ) ); // => true or false

推荐阅读