对象的访问方式
var obj = {
name: "Carrot",
"for": "Max",//'for' 是保留字之一,使用'_for'代替
details: {
color: "orange",
size: 12
}
};
/*添加和打印*/
obj["detail"]["color"]; //orange
obj.detail.color; //orange
obj["test"]="测试";
obj.test="测试";
//对于数组方式没有过多地显示
对象的不同遍历方法
1、常见简单数组遍历
var test=[1,2,3,4,5];
for(let i=0;i<test.length;i++){
//对于test[i]进行操作 1,2,3,4,5
};
/*对于对象来说i是key,简单数组是索引值*/
for (let i in test) {
console.log(test[i]); // 1,2,3,4,5
};
for (let i of test) {
console.log(i); //1,2,3,4,5
};
/*map(function(value,index,arr){})返回的是一个新数组,按照原始数据顺序进行处理*/
test.map(function(value){
console.log(value); //1,2,3,4,5
});
/*filter返回的是一个数组*/
test.filter(function(value){
//操作value
});
test.forEach(function(value){
console.log(value); //1,2,3,4,5
});
//如果使用jQuery
$.each(test, function(index,elem) {
console.log(elem); //1,2,3,4,5
});
2、常见的json对象的遍历
var testJson=[
{'a':'11','b':'22'},
{'a':'111','b':'222'}
];
//普通的for语句
for(let i=0;i<testJson.length;i++){
console.log(testJson[i]); //{'a':'11','b':'22'}
}
for (let key in testJson[0]) {
console.log(key); //a,b
};
$.each(testJson, function(index,elem) {
console.log(elem);//{'a':'11','b':'22'}
});
testJson.forEach(function(elem,index){
console.log(elem); //{'a':'11','b':'22'}
console.log(elem['a']);//11
})
//这是我们比较常见的遍历方法
这些只是将常用的知识简单梳理一下便于快速查阅。