我正在使用$.each
函数循环对象,但我得到的是不变的值。
我的代码出了什么问题?
var mainPageCircle = {
circles: {
c1: {
color: '#730000',
text: 'Content'
},
c2: {
color: '#004f74',
text: 'Consulting'
},
c3: {
color: '#146c00',
text: 'Commerce'
}
},
radious: 100,
stroke: 10,
strokeColor: '#fff',
opacity: 0.7
}
$.each(mainPageCircle, function(key, value) {
var circles = value.circles,
radious = value.radious;
$.each(circles, function(index, c) {
console.log(index, c); // i am getting error; i need index should be 0,1,2 and c should be : c1,c2,c3 values
})
})
答案 0 :(得分:3)
这样的东西?
var mainPageCircle = {
circles :{
c1:{color:'#730000',text:'Content'},
c2:{color:'#004f74',text:'Consulting'},
c3:{color:'#146c00',text:'Commerce'}
},
radious:100,
stroke:10,
strokeColor:'#fff',
opacity:0.7
};
var i = 0;
$.each(mainPageCircle.circles, function(){
console.log(i, this);
//i: current index
//this: c1, c2 etc
//use properties on this to fetch the values
//this.color for example
i++;
});
您将无法在示例中将key
用作索引整数,因为它将获取对象键,而不是循环中的当前索引。
答案 1 :(得分:2)
我不确定你的意图是什么,但你可能想做的事情如下:
var mainPageCircle = {
circles :{
c1:{color:'#730000',text:'Content'},
c2:{color:'#004f74',text:'Consulting'},
c3:{color:'#146c00',text:'Commerce'}
},
radious:100,
stroke:10,
strokeColor:'#fff',
opacity:0.7
}
var circles = mainPageCircle.circles,
radious = mainPageCircle.radious;
$.each(circles, function (index, c) {
console.log(index,c); // c1, props, etc...
console.log(parseInt(index,10)); // 1,2,3...
});
答案 2 :(得分:2)
您的每个项目都在运行mainPageCircle的所有项目,而不仅仅是其中定义的圈子。这可能更符合您的目标:
var mainPageCircle = {
circles :{
c1:{color:'#730000',text:'Content'},
c2:{color:'#004f74',text:'Consulting'},
c3:{color:'#146c00',text:'Commerce'}
},
radious:100,
stroke:10,
strokeColor:'#fff',
opacity:0.7
}
$.each(mainPageCircle.circles , function (key,value) {
var circles = value,radious = mainPageCircle.radious;
$.each(circles, function (index,c) {
console.log(index,c);
});
});