0
点赞
收藏
分享

微信扫一扫

evalFn 字符串转执行函数 附带JSONParse函数

const evalFn = (fn) => {
    var Fun = Function // 一个变量指向Function,防止前端编译工具报错
    return new Fun('return ' + fn)()
  }

/**
 * * JSON反序列化,支持函数和 undefined
 * @param data
 */
  const JSONParse = (data) => {
    return JSON.parse(data, (k, v) => {
      // 过滤函数字符串
      if (excludeParseEventKeyList.includes(k)) return v
      // 过滤函数值表达式
      if (typeof v === 'string') {
        const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
        if (someValue) return v
      }
      // 还原函数值
      if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
        return evalFn(`(function(){return ${v}})()`)
      } else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
        const baseLeftIndex = v.indexOf('(')
        if (baseLeftIndex > -1) {
          const newFn = `function ${v.substring(baseLeftIndex)}`
          return evalFn(`(function(){return ${newFn}})()`)
        }
      }
      return v
    })
  }

测试代码

let a2 = new Function(`return function () {
const a = {
b: '333'
}
return a }()`)()

evalFn 字符串转执行函数 附带JSONParse函数_编译工具

evalFn 字符串转执行函数 附带JSONParse函数_JSON_02

---------------------------------------------
生活的意义就是你自己知道你要做什么,明确目标。没有目标,后面都是瞎扯!

https://pengchenggang.gitee.io/navigator/

SMART原则:

目标必须是具体的(Specific)
目标必须是可以衡量的(Measurable)
目标必须是可以达到的(Attainable)
目标必须和其他目标具有相关性(Relevant)
目标必须具有明确的截止期限(Time-based)



举报

相关推荐

0 条评论