本篇文章给大家带来的内容是关于JavaScript对象序列化、toString()与valueOf()的用法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
序列化
JSON.stringify()处理对象
let obj = {
val: undefined,
a: NaN,
b: Infinity,
c: new Date(),
d: { e: 'nice' },
y: Object
}
console.log(JSON.stringify(obj))
//输出 "{ "a": null, "b": null, "c": "2019-03-13T12:01:44.295Z", "d": "{ "e": "nice" }" }"
当对象的value为undefined和Object时会被忽略,为NaN和Infinity为null,对象实例如d,为key和value都加上双引号
JSON.stringify()处理数组
let arr = [undefined, Object, Symbol(""), { e: 'nice' }]
console.log(JSON.stringify(arr))
//输出 "[null, null, null, { "e": "nice" }]"
自定义序列化
可以重写toJSON()方法进行自定义序列化
let obj = {
x: 1,
y: 2,
re: {
re1: 1,
re2: 2,
toJSON: function(){
return this.re1 + this.re2;
}
}
}
console.log(JSON.stringify(obj))
//输出 "{ "x":1, "y":2, "re":3 }"
对象的toSting()
let obj = { x:1, y:2 }
console.log(obj.toString()) //输出 "[object Object]"
obj.toString = function(){
return this.x + this.y;
}
"Result" + obj; //输出 "Result3" 调用了toString
+obj; //输出 "3" 调用了toString
obj.valueOf = function(){
return this.x + this.y + 100;
}
"Result" + obj; //输出 "Result103" 调用了toString
当toString和valueOf都存在时,在进行操作时,都会尝试转换成基本类型,先找valueOf,如果返回基本类型,这只调用valueOf,如果不是,比如是对象的话,就去找toString,如果也返回Object,就会报错
以上就是JavaScript对象序列化、toString()与valueOf()的用法介绍的详细内容
JavaScript对象序列化、toString()与valueOf()的用法介绍
转载wx61133eeec1457 博主文章分类:javascript
文章标签 json 序列化 自定义 javascript 对象序列化 文章分类 JavaScript 前端开发
下一篇:JavaScript版本说明
-
2.4 对象的序列化与反序列化
例对象。这种情况下就要使用对象的序列化和反序列化。
java jvm 开发语言 序列化 System -
对象的序列化与反序列化详解
Java对象序列化时参与序列化的内容包含以下几个方面:1.属性,包括基本数据类型、数组以及其他对象的引用
序列化 对象 java 反序列化 -
JavaScript的valueOf和toString
高阶函数的使用,替代for循环 拓展问题 1. 还有那些类似对象方法? 1. 实际开发中如何巧妙的利用?
javascript for循环 实际开发 高阶函数 对象方法 -
python批量做excel周报
最近由于比赛需求,需要大量的数据支持系统的功能测试。然后比较坑的是,所有的源数据都是来自Excel文件格式。虽然我们可以用Navicat Premium 12类似的工具导入,但是这类的工具似乎只有一个一个导入excel文件的功能,并不能满足我们有3600多张Excel表的需求呀。 于是就想到了
python批量做excel周报 Pandas Python Excel 批量处理