var person = {
name: "刘亦菲",
age: 35,
sex: '女'
}
【JSON 转换 为 字符串】
var x = JSON.stringify(person);
console.log(x)
【字符串 转换为 对象】
var y = JSON.parse(x)
var y = eval(`(${x})`)
console.log(y)
3 JSON格式的遍历
<script type="text/javascript">
var people = {
"男明星": [{
"name": "梁朝伟",
"age": "40"
},
{
"name": "刘德华",
"age": "42"
},
{
"name": "彭于晏",
"age": "29"
}
],
"女明星": [{
"name": "刘嘉玲",
"age": "40"
},
{
"name": "张敏",
"age": "41"
},
{
"name": "张柏芝",
"age": "30"
},
{
"name": "朱茵",
"age": "38"
}
]
}
// 获取页面元素
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
//【下拉列表添加数据】
//初始化添加数据
for (var i in people) {
s1.options.add(new Option(i))
}
for (var i of people['男明星']) {
s2.options.add(new Option(i.name))
}
// 【下拉列表事件】
s1.onchange = function() {
//清空数据
s2.options.length=0;
// 添加数据
for (var j of people[this.options[this.selectedIndex].innerText]) {
s2.options.add(new Option(j.name))
}
}
</script>