javascript - 如何制作一个可以将任何看起来像 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()函数呢?
提前致谢
解决方案
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
推荐阅读
- vim - Vim - 何时执行 autocmd 定义的 {cmd} 命令?
- java - 尝试使用 java 连接到 mysql 并显示
- r - 使用行总和在 R 数据框中创建一个新列
- haproxy - 在 Keepalived 中没有调用“通知”
- navigation - 文档可见性更改与窗口模糊/焦点,有什么区别,何时使用?
- swift - 如何获取 Apple Watch 显示半径?
- javascript - 如何在 vue+ts 中正确注册组件?
- python - view.py django 中的递归错误
- android - 如何防止 READ_PHONE_STATE Android 权限
- reactjs - 什么是 redux 中的 props 方法是如何附加到它的