JSON.stringify()
converts a value to JSON notation representing it:- Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
Boolean
,Number
, andString
objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.- If
undefined
, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored tonull
(when it is found in an array).JSON.stringify
can also just returnundefined
when passing in "pure" values likeJSON.stringify(function(){})
orJSON.stringify(undefined)
. - All symbol-keyed properties will be completely ignored, even when using the
replacer
function. - Non-enumerable properties will be ignored
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify('foo'); // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
// '"2006-01-02T15:04:05.000Z"'
JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'
JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
// '{"x":[10,null,null,null]}'
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
if (typeof k === 'symbol') {
return 'a symbol';
}
});
// '{}'
// Non-enumerable properties:
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false },
y: { value: 'y', enumerable: true } }) );
// '{"y":"y"}'
----------------------------alert(JSON.stringify(/[a-z]/g)); // {}
@reference_0_mozilla
No comments:
Post a Comment