How to solve this minimal js code issue?
My inputs are: an array of object names and objects. I want to loop through the array for object name and then output something from corresponding object. My code is as follows:
options=["bold","italic"] ;
var bold ={
action: function(){
alert("<strong>just bold</strong>");
},
b_p: "-40px bold"
};
var italic ={
action: function(){
alert("<em>an italic</em>");
},
b_p: "-20px italic"
};
for(i=0;i<options.length;++i)
{
document.write(options[i].b_p);
}
My 开发者_运维技巧desired output: "-40px bold -20px italic" but I get an error saying: "undefined undefined".
Please help me to find out my mistake/ignorance here.
Thanks.
/******/ Update: the problem is solved below :-) Thanks communtiy
Instead of passing the names, pass an object array:
var bold = {
action: function(){
alert("<strong>just bold</strong>");
},
b_p: "-40px bold"
};
var italic = {
action: function(){
alert("<em>an italic</em>");
},
b_p: "-20px italic"
};
var options = [ bold, italic ]; // symbols, not strings
for(var i=0;i<options.length;++i)
{
document.write(options[i].b_p);
}
Nothing else would really need to change.
A few problems here:
options=["bold","italic"] ;
should be options=[bold,italic];
and should be after the declaration of the bold
and italic
vars
Also, for(i=0;i<options.length;++i)
should be for(i=0;i<options.length;i++)
(note the post-increment instead of a pre-increment)
So to sum it up:
var bold ={
action: function(){
alert("<strong>just bold</strong>");
},
b_p: "-40px bold"
};
var italic ={
action: function(){
alert("<em>an italic</em>");
},
b_p: "-20px italic"
};
var options=[bold,italic];
for(i=0;i<options.length;i++)
{
document.write(options[i].b_p);
}
Here is a much more cleaner approach:
var options = {
"bold": {
"action": "<strong>just bold</strong>",
"b_p": "-40px bold"
},
"italic": {
"action": "<em>an italic</em>",
"b_p": "-20px italic"
}
};
for (var i in options) {
document.write(options[i]["b_p"] + "<br />")
}
Example: http://jsfiddle.net/sea2d/
If you wanted to alert your action, you could just use:
alert(options["bold"]["action"]);
精彩评论