gpt4 book ai didi

javascript - 如何从 React Native 中的字符串运行 javascript 逻辑?

转载 作者:行者123 更新时间:2023-11-30 08:22:25 26 4
gpt4 key购买 nike

在我的应用程序中,第三方游戏开发人员将根据我的模板编写简单的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com