javascript - JavaScript 给定的字符串是否作为变量和函数存在
问题描述
我有一个变量,它有一个成员变量,它是一个函数
let test = {
setup: function() { ...}
}
从其他来源,我得到字符串“test.setup”
我如何检查是否
a.) 变量测试存在
b.) 变量 test 有一个名为 setup 的子项
c.) 子设置是一个函数?
d.) 调用函数
我已经测试过了
let variableName = "test.setup";
window[variableName]
// undefined
{}.toString.call(variableName ) === '[object Function]'
// VM2052:1 Uncaught SyntaxError: Unexpected token .
window.hasOwnProperty("test")
// false
如果你能解决我的问题,那就太好了。对我来说,看看是否有这样的函数并在它存在时调用它就足够了。否则通知用户没有这样的功能。
非常感谢您提前
解决方案
最简单但不太安全的方法是使用eval()
. 永远不要使用eval()
用户生成的数据,因为它是一种攻击媒介。
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
如果在未定义的变量上评估“.setup”,您将收到错误消息。所以你可以try/catch
用来处理这个。
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
推荐阅读
- python - 为什么即使在迁移之后也会抛出错误?(没有这样的表:accounts_userstripe)
- python - 无法为 Docker 安装 software-properties-common
- android-studio - 如何解决 sqlite_error
- java - 如何在显示类路径异常的android studio构建问题中修复Gradle
- css - 如何在 Bootstrap-vue 中更改导航栏链接的颜色
- gensim - 如何衡量 Doc2vec 模型的准确性?
- scala - Scala如何在hashmap项上调用未来函数
- oauth-2.0 - 将 google oauth2 与 php 邮件程序一起使用
- asp.net-ajax - 如何修复 scriptresource 和 webresource.axd 加载问题
- c - 如何对字符串进行插值搜索?