JS Object数据类型与json序列化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>、
<script>
// 方法1
var obj = new Object();
obj.name = "huchangxi"
obj.age = 23
console.log(obj.name) // huchangxi
console.log(obj.age) // 23
// 方法2
var name = "huchangxi"
var obj2 = {
name: "huchangxi",
age: "22"
}
obj2.name = "xxx"
console.log(obj2) // {name: 'xxx', age: '22'}
var attr = "age"
console.log(obj2) // {name: 'xxx', age: '22'}
console.log(obj2.name) // xxx
console.log(obj2["name"]) // xxx
console.log(obj2.age) // 22
console.log(obj2["age"]) // 22
console.log(obj2[attr]) // 22
for (var k in obj2){
console.log(k,obj2[k]) // name xxx age 22
}
// 序列化方法: JSON.stringify()
var jsonData = JSON.stringify(obj2)
// 反序列化方法: JSON.parse()
JSON.parse(jsonData)
</script>
</head>
<body>
<h1>welcome to JS!</h1>
</body>
</html>
![](https://img2022.cnblogs.com/blog/1413093/202206/1413093-20220604195823269-1397217531.png)