在凯尔辛普森的书中 You Don't Know JS: this & Object Prototypes , 他写了这篇关于如何复制对象的主题:
One subset solution is that objects which are JSON-safe (that is, can be serialized to a JSON string and then re-parsed to an object with the same structure and values) can easily be duplicated with:
var newObj = JSON.parse( JSON.stringify( someObj ) );
Of course, that requires you to ensure your object is JSON safe. For some situations, that's trivial. For others, it's insufficient.
什么是“JSON 安全”对象?我用 JavaScript 运行了一些测试,到目前为止,大多数东西(数组、数字、字符串、对象)都可以使用上面的行复制,除了方法(foo.bar
),当试图复制一个方法,undefined
被插入到复制对象中方法的位置。
最佳答案
要让 foo
<=> JSON.parse(JSON.stringify(foo))
为真,我们必须能够表示 foo
在 JSON format .
JSON 只支持:
Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers like NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.
String: a sequence of zero or more Unicodecharacters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
Boolean: either of the values true or false
Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.
Object: an unordered collection of name/value pairs where the names (also called keys) are strings. Since objects are intended to represent associative arrays,[12] it is recommended, though not required,[13] that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
null: An empty value, using the word null
在javascript中,JSON safe object
的概念基本上是指可以无损地用JSON格式表示的javascript对象。
关于javascript - 什么是 JSON 安全对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416370/