1

我正在使用$.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
    })
})
4

3 回答 3

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在示例中将其用作索引整数,因为它将获取对象键,而不是循环中的当前索引。

小提琴

于 2012-11-06T09:00:18.987 回答
3

您的 each 正在运行 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);
        });
});
于 2012-11-06T09:11:28.097 回答
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...
});
于 2012-11-06T09:01:10.913 回答