JSON.parse Reviver函数是否具有n + 1个键? [英] JSON.parse reviver function has n+1 keys?

查看:81
本文介绍了JSON.parse Reviver函数是否具有n + 1个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试代码重载,可以在解析JSON字符串时提供reaviver函数.

因此,此代码:

JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; }).p;

产量10(确定).

但是后来我问自己:这是什么?让我们删除它!:

But then I asked myself, 'what is this if (k === "") thing?' Lets remove it!:

JSON.parse('{"p": 5}', function(k, v) { return v*2;}).p; //undefined !!

也许因为5是整数?让我们尝试parseInt:

Maybe because 5 is an integer? Let's try with parseInt:

JSON.parse('{"p": 5}', function(k, v) { return parseInt(v)*2;}).p; //undefined !!

很奇怪...

所以我想看看是哪个键(尽管这里只有一个)引起了麻烦:

So then I wanted to see which keys (although there is only one here) are causing the trouble:

JSON.parse('{"p": 5}', function(k, v) { alert(v)}).p;

有2条警报:

  • 5

[object Object]

IMHO kv用于keyvalue,实际上这里只有一个键.

IMHO k and v are for key and value, and indeed there is only one key here.

这是什么?而且为什么,我必须检查if (k === "")吗?

What is this other alert? And why do I have to check if (k === "")?

推荐答案

答案在您提供的链接中...

The answer is in the link you provided...

最终,将使用空字符串和最高值调用reviver,以允许转换最高值.

The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value.

k === ""

这篇关于JSON.parse Reviver函数是否具有n + 1个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆