解析:该题目考察我们对数据类型的认识
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSON.stringify实现</title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
function stringify(value) {
const typeMap = {
'string': true,
'number': true,
'boolean': true,
'object': value instanceof RegExp || value instanceof Date || value === null
};
const type = typeof value;
if (typeMap[type]) {
return String(value);
} else if (typeof value == 'function') {
return value.toString()
} else if (Array.isArray(value)) {
return '[' + value.map(item => stringify(item)).join(',') + ']';
} else if (type === 'object') {
let properties = Object.keys(value).map(key => '"' + key + '":' + stringify(value[key]));
return '{' + properties.join(',') + '}';
} else {
return undefined;
}
}
// 示例数据
let data = {
name: 'Alice',
age: 30,
isStudent: true,
hobbies: ['reading', 'coding', {
sayHello: function() {
console.log('Hello!');
},
regex: /pattern/g,
date: new Date(),
}],
address: {
city: 'Shanghai',
country: 'China'
},
sayHello: function() {
console.log('Hello!');
},
regex: /pattern/g,
date: new Date(),
unrf: undefined,
emptyValue: null
};
// 序列化为 JSON 字符串
let jsonString = stringify(data);
console.log(jsonString);
// {"name":Alice,"age":30,"isStudent":true,"hobbies":[reading,coding,{"sayHello":function() {
// console.log('Hello!');
// },"regex":/pattern/g,"date":Tue Jul 11 2023 10:04:56 GMT+0800 (中国标准时间)}],"address":{"city":Shanghai,"country":China},"sayHello":function() {
// console.log('Hello!');
// },"regex":/pattern/g,"date":Tue Jul 11 2023 10:04:56 GMT+0800 (中国标准时间),"unrf":undefined,"emptyValue":null}
</script>