Comments (3)
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.
@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.
这下通了,之前困扰了我很久,感谢大神
from fe-practice-hard.
Related Issues (20)
- 第 110 期(数据结构-数组):清空数组
- 第 111 期(W3C 标准-JavaScript-Date):五种获取指定日期毫秒数的方法
- 第 112 期(W3C 标准-HTML):table的colgroup和col
- 第 113 期(W3C 标准-JavaScript-异步):async 和 await
- 第 114 期(W3C标准-CSS-伪类&伪元素):focus-within 伪类
- 第 115 期(W3C标准-CSS-语法):CSS 单位
- 第 116 期(W3C 标准-JavaScript):atob & btoa —— base64 的解码编码
- 第 117 期(JavaScript-DOM):监听页面DOM元素的插入
- 第 118 期(算法-排序):数组乱序
- 第 119 期(JavaScript-DOM):DocumentFragment - 文档片段
- 第 120 期(W3C 标准-JavaScript-事件):pagehide 和 pageshow
- 第 121 期(W3C 标准-JavaScript-DOM):dataset
- 第 122 期(数据结构-哈希):哈希表
- 第 123 期(W3C标准-CSS-伪类&伪元素):表单验证伪类
- 第 124 期(W3C 标准-JavaScript):unicode码互转
- 第 125 期(算法-递归):统计子类目数量
- 第 126 期(W3C 标准-JavaScript):iframe父子通信
- 第 127 期(W3C标准-CSS-绘制):border-radius
- 第 128 期(技巧):关于logo显示的SEO小技巧
- 第 129 期(W3C标准-CSS-动画):跳动的心 for 10.24程序员节
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fe-practice-hard.