1.数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var course = ['php', 'js', 'css', 'java','c++'];
console.log(course.length);
console.log(course[2]);
console.log(Array.isArray(course));
//遍历一个数组
for(var i = 0; i <course.length; i++){
console.log(course[i]);
}
course.forEach(function(item, index, array){
document.body.innerHTML += "<li>" + index + item + "</li>";
})
document.body.innerHTML += "<hr>";
//使用slice获取数组元素
console.log(course.slice(0,2));
console.log(course.slice(0));
//使用splice实现数组元素的删除,插入,替换
course.splice(2, 0,'html');
console.log(course);
course.splice(2, 1,'go');
console.log(course);
course.splice(2,1);
console.log(course);
</script>
</body>
</html>
2.对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var staff = {
message:{
id: 108,
name:'peter',
},
department:'office',
grade:'primary',
postion:'php开发工程师',
salary:8000,
}
console.table(staff);
console.log(staff['message'].name);
for (key in staff){
console.log(staff[key]);
}
</script>
</body>
</html>
3.将js的对象转换为json格式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var staff = {
message:{
id: 108,
name:'peter',
},
department:'office',
grade:'primary',
postion:'php开发工程师',
salary:8000,
sex:undefined,
}
var jsonStr = JSON.stringify(staff);
console.log(jsonStr);
var jsonStr = JSON.stringify(staff,['department','postion']);
console.log(jsonStr);
jsonStr = JSON.stringify(staff,function(key, value){
switch (key) {
case 'message':
return '这是我的秘密';
break;
case 'salary':
return '10000';
default:
return value;
}
});
console.log(jsonStr);
</script>
</body>
</html>
总结:js中的数组和PHP中的索引数组类似,js中的对象和PHP中的关联数组类似。json格式在前后端交互时用的非常多。