最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For loop for object? - Stack Overflow

programmeradmin1浏览0评论

I have the next code in javascript. I deleted some unnecessary items because it went to long.

var options = {
    dhcode: true,
    mands: {
        bold: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'bold',
            param: null
        },
        italic: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'italic',
            param: null
        },
        underline: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'underline',
            param: null
        }
    }
}

Now i want to get al data in the optionsmands object. But everything what i try don't work. This is what i am trying:

for(var i=0;i<optionsmands.length;i++) {
alert(optionsmands[i].cmd);
}

Please help me.

I have the next code in javascript. I deleted some unnecessary items because it went to long.

var options = {
    dhcode: true,
    mands: {
        bold: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'bold',
            param: null
        },
        italic: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'italic',
            param: null
        },
        underline: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'underline',
            param: null
        }
    }
}

Now i want to get al data in the options.mands object. But everything what i try don't work. This is what i am trying:

for(var i=0;i<options.mands.length;i++) {
alert(options.mands[i].cmd);
}

Please help me.

Share Improve this question edited Mar 3, 2010 at 18:02 ghoppe 21.8k3 gold badges31 silver badges21 bronze badges asked Mar 3, 2010 at 17:53 TimoTimo 7,4157 gold badges26 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

.length is a property of arrays, what you have is an object.

Try:

for(var key in options.mands) {
    alert(options.mands[key].cmd);
}

Have a look at how-to-loop-through-javascript-object-literal-with-objects-as-members.

Essentially:

for (var key in options.mands) {
   alert(  options.mands[key].enabled );
   ...
}
for(var i in options.mands){
   alert(i); //bold, italic, underline
   alert(options.mands[i].cmd);
}
发布评论

评论列表(0)

  1. 暂无评论