作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的应用程序中,第三方游戏开发人员将根据我的模板编写简单的 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”。
这样做的主要危险在于确保您的所有开发人员都知道哪些参数将传递给他们编写的“字符串”,以及这些参数的数据模型是什么。
关于javascript - 如何从 React Native 中的字符串运行 javascript 逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276496/
我是一名优秀的程序员,十分优秀!