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

发布时间 2023-12-06 15:22:31作者: 彭成刚
  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
    })
  }