Giter Club home page Giter Club logo

Comments (3)

AMY-Y avatar AMY-Y commented on July 4, 2024 2
if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: (function () {
      var toString = Object.prototype.toString;
      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
      return function stringify(value) {
        if (value == null) {
          return 'null';
        } else if (typeof value === 'number') {
          return isFinite(value) ? value.toString() : 'null';
        } else if (typeof value === 'boolean') {
          return value.toString();
        } else if (typeof value === 'object') {
          if (typeof value.toJSON === 'function') {
            return stringify(value.toJSON());
          } else if (isArray(value)) {
            var res = '[';
            for (var i = 0; i < value.length; i++)
              res += (i ? ', ' : '') + stringify(value[i]);
            return res + ']';
          } else if (toString.call(value) === '[object Object]') {
            var tmp = [];
            for (var k in value) {
              if (value.hasOwnProperty(k))
                tmp.push(stringify(k) + ': ' + stringify(value[k]));
            }
            return '{' + tmp.join(', ') + '}';
          }
        }
        return '"' + value.toString().replace(escRE, escFunc) + '"';
      };
    })()
  };
}

虽然这是一道送分题,作为一直小白还是有点小疑惑请教

//对于
 eval('(' + sJSON + ')');
//在浏览器控制台里
var json={"a":"b","c":"d"}
eval(json);
{a: "b", c: "d"}//正常
var json={"a":"b","c":"d"}
eval("("+json+")");//报错
VM191:1 Uncaught SyntaxError: Unexpected identifier
    at <anonymous>:2:14
(anonymous) @ VM190:2
var json={"a":"b","c":"d"}
eval('('+json+')');//报错
VM205:1 Uncaught SyntaxError: Unexpected identifier
    at <anonymous>:2:14
(anonymous) @ VM204:2

这是为毛啊?

from fe-practice-hard.

wingmeng avatar wingmeng commented on July 4, 2024 1

@AMY-Y 这题以及上述参考答案我是在 codewars 上看到的,我作答时用的也是 eval。new Function 这种方式非常巧妙的利用了 js 中的函数构造器,无论在性能、安全性还是代码健壮性上,都要比 eval 方式好得多。
你说的那两个报错的问题,是因为给 eval 的传参不对,它接收的应该是字符串,不能是一个对象,所以按 var json='{"a":"b","c":"d"}' 或者 var json="{a:\"b\",c:\"d\"}" 这样写就没问题,eval('('+json+')') 就能将其正确解析为对象了。
相关资料:https://www.jianshu.com/p/5d6523017981

from fe-practice-hard.

AMY-Y avatar AMY-Y commented on July 4, 2024

这下通了,之前困扰了我很久,感谢大神

from fe-practice-hard.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.