Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:json就是js对象字面量格式的字符串 , 仅此而已
可以直接为变量赋值为数组格式的值。
//数组对象,js中的数组只能直接写索引数组,与PHP一样
var computer = ["chassis", "screen", "mouse", "keyboard"];
console.log(computer[2]); //mouse
//关联数组需要单独赋值,实际上是该数组对象的属性,可以通过属性的方式访问
computer["energy"] = "electric"; //以数组方式赋值
computer.interface = "USB"; //以属性方式赋值
console.log(computer["energy"]); //electric
console.log(computer.energy); //electric
console.log(computer.interface); //USB
console.log(Array.isArray(computer)); //检测是否是数组:true
//slice()和splice()方法
//slice()获取数组中的部分元素,参数为开始位置和结束位置
console.log(computer.slice(2)); //没有第二个参数默认到结束位置
console.log(computer.slice(0, 2)); //Array [ "chassis", "screen" ]
console.log(computer.slice(3, 6)); //属性部分没有出现:Array [ "keyboard" ]
//splice()插入,删除,替换数组中的元素
computer.splice(1, 1); //删除一个元素,起始位置1,删除数量1
console.log(computer); //Array(3) [ "chassis", "mouse", "keyboard" ]
computer.splice(1, 2, "screen", "sdv"); //替换2个元素
console.log(computer); //Array(3) [ "chassis", "screen", "sdv" ]
computer.splice(1, 0, "mouse", "keyboard"); //插入2个元素
console.log(computer); //Array(5) [ "chassis", "mouse", "keyboard", "screen", "sdv" ]
//遍历数组元素
//forEach方法,只能遍历出索引部分
computer.forEach(function (item, index, array) {
console.log(item); //值
console.log(index); //下标
console.log(array); //原数组
});
//for,只能遍历出索引部分
for (var i = 0; i < computer.length; i++) {
console.log(computer[i]);
}
//以上输出:chassis,mouse,keyboard,screen,sdv
//for in, 关联部分也能遍历出来
for (var index in computer) {
console.log(computer[index]);
}
//以上输出:chassis,mouse,keyboard,screen,sdv,electric,USB
//创建一个对象
var computer = {
主机: "华硕",
显示屏: "戴尔",
鼠标: "罗技",
键盘: "雷蛇",
};
console.log(typeof computer); //object
var myJson = JSON.stringify(computer); //转换为json字符串
console.log(myJson); //{"主机":"华硕","显示屏":"戴尔","鼠标":"罗技","键盘":"雷蛇"}
var myObj = JSON.parse(myJson); //json字符串转为js对象
console.log(myObj); //Object { "主机": "华硕", "显示屏": "戴尔", "鼠标": "罗技", "键盘": "雷蛇" }
//遍历对象的属性
for (var item in myObj) {
console.log(myObj[item]);
}
//华硕 显示屏 戴尔 罗技 雷蛇