给定一个像这样的 block :
var foo = {
"regexp": /^http:\/\//,
"fun": function() {},
}
将其存储在 JSON 中的正确方法是什么?
最佳答案
您必须将 RegExp 作为字符串存储在 JSON 对象中。然后,您可以从字符串构造一个 RegExp 对象:
// JSON Object (can be an imported file, of course)
// Store RegExp pattern as a string
// Double backslashes are required to put literal \ characters in the string
var jsonObject = { "regex": "^http:\\/\\/" };
function fun(url) {
var regexp = new RegExp(jsonObject.regex, 'i');
var match;
// You can do either:
match = url.match(regexp);
// Or (useful for capturing groups when doing global search):
match = regexp.exec(url);
// Logic to process match results
// ...
return 'ooga booga boo';
}
至于函数:无论如何,它们不应该用 JSON 或 XML 表示。函数在 JS 中可以被定义为对象,但其主要目的仍然是封装一系列命令,而不是作为基本数据的包装器。
关于javascript - 我可以将 RegExp 和 Function 存储在 JSON 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328119/