javascript - 如何从 React Native 中的字符串运行 javascript 逻辑?
问题描述
在我的应用程序中,第三方游戏开发人员将根据我的模板编写简单的 JavaScript 逻辑。他们会将他们的代码输入文本框(在线),我会将他们的代码存储为字符串。
例如,一位游戏开发者会这样写:
const examineItem = (user, item, app) => { //we will pass `user` and `item` with our own methods
//Developer writes his/her own logic
if(user.intelligence > 50){
return({ result: "You see a rock!"});
}else{
return({ result: "You see nothing"});
}
};
在我的 React Native 应用程序中,如何将这个字符串代码“转换”为可运行的函数?我需要翻译吗?我是否使用eval
(已弃用)?
我从哪里开始?
解决方案
其实也不算太难。像这样使用“新函数”运算符:
const examineItem = (user, item, app) => {
// Developer writes his/her own logic
const devString = 'return user.intelligence > 50'
// You can pass as many arguments as you want, just keep the string last:
const devFunc = new Function('user', 'item', 'app', devString)
// Make sure to pass all the arguments to the call:
if(devFunc(user, item, app)){
return({ result: "You see a rock!"});
} else{
return({ result: "You see nothing"});
}
};
// Testing it:
const user = { intelligence: 60 }
const res = examineItem(user, null, null)
console.log(res) // { result: "You see a rock!"}
我刚刚测试了这段代码,它应该可以工作。你可以从任何你想要的地方拉出“devString”。
这样做的主要危险只是确保您的所有开发人员都知道哪些参数将传递给他们编写的“字符串”,以及这些参数的数据模型是什么。
推荐阅读
- java - 如何在 JPA 中找到与规范和可分页关系密切的所有内容?
- c++ - What does a typecast at the beginning of an arithmetic expression apply to?
- python - 烧瓶休息加。为什么我的 Api 没有“marshall_with”属性?
- ios - gl-react 渲染 IOS 上的旋转照片(仅限 IOS 照片)
- python-3.x - Ansible:Jinja2 无法正确读取字典对象
- javascript - 为什么在设置 Mongoose 连接时在 .then() 中使用 console.log() 时不打印?
- nlp - 聚类后如何测量聚类内句子之间的相似度?
- python - FMU机器学习模型
- javascript - TS RadioGroup 在更改处理程序上返回类型字符串而不是可能的字符串数组
- css - OnePlus移动问题在媒体通话中没有响应