首页 > 解决方案 > 用对象理解 .map 和 Stringify

问题描述

我在 JS 上尝试不同的东西来了解它们的性能。

对于我的测试,我想了解如果我 JSON.stringify(something)直接做而不是用 Map 做会发生什么。

JSON.stringify(something)直接用

var rockets = [
    { country:'Russia', launches:32 },
    { country:'US', launches:23 },
    { country:'China', launches:16 },
    { country:'Europe(ESA)', launches:7 },
    { country:'India', launches:4 },
    { country:'Japan', launches:3 }
];

console.log(JSON.stringify(rockets))

我在控制台中得到这个的地方

[{"country":"Russia","launches":32},{"country":"US","launches":23},{"country":"China","launches":16},{"country":"Europe(ESA)","launches":7},{"country":"India","launches":4},{"country":"Japan","launches":3}]

Map我得到了这个

var rockets = [
    { country:'Russia', launches:32 },
    { country:'US', launches:23 },
    { country:'China', launches:16 },
    { country:'Europe(ESA)', launches:7 },
    { country:'India', launches:4 },
    { country:'Japan', launches:3 }
];

console.log(rockets.map(d => JSON.stringify(d)))

我在哪里得到这样的东西

["{"country":"Russia","launches":32}", "{"country":"US","launches":23}", "{"country":"China","launches":16}", "{"country":"Europe(ESA)","launches":7}", "{"country":"India","launches":4}", "{"country":"Japan","launches":3}"]

现在,我试图理解代码并且JSON.stringify(something)确实有意义,但是当我查看时Map,我看到"添加了一个[,但我无法理解它是从哪里来的?

另外,chrome控制台和stackoverflow的结果不同,有人能解释一下为什么我\以前"在stackoverflow结果中看到过吗

例子[ "{\"country\":\"Russia\",\"launches\":32}",

总而言之,我的主要问题 是 .map 如何与 json stringify 一起使用?

标签: javascript

解决方案


第一个JSON.stringify(rockets)结果是一个长字符串,其中包含序列化数据,可以用JSON.parse.

第二个rockets.map(d => JSON.stringify(d)结果是一个数组,其中的每一项都是一个字符串,可以反序列化回一个小对象。

较低代码中 s之前的反斜杠"有点令人困惑,这是因为堆栈控制台用 . 分隔字符串"。如果使用它会更清楚'- 使用's,底部结果看起来像

[
  '{"country": "Russia","launches": 32}',
  '{"country": "US","launches": 23}',
  '{"country": "China","launches": 16}',
  // ...
]

这是第二个片段产生的完全相同的数组

var rockets = [
    { country:'Russia', launches:32 },
    { country:'US', launches:23 },
    { country:'China', launches:16 },
    { country:'Europe(ESA)', launches:7 },
    { country:'India', launches:4 },
    { country:'Japan', launches:3 }
];

console.log(rockets.map(d => JSON.stringify(d)))

除了它以更易于阅读的格式显示之外,因为数组项(字符串)以's 分隔,因此字符串中的文字"s 不需要先用反斜杠进行转义。

(就像一条线

const str = 'foo'

相当于使用

const str = "foo"

, 如何

const str2 = 'fo"o'

相当于

const str2 = "fo\"o"

:也就是说,要表示您用作字符串分隔符的相同字符,您必须先在其前面放置一个反斜杠)

请注意,JSON 字符串要求键和字符串值用双引号括起来",但对象文字(如上面显示的)不需要。


推荐阅读