I've been looking for a special argument and/or variable that can do this i.e.:
function myFunction(arg1, arg2) {
switch(arg2) {
case FIRSTCHOICE:
// Code
break;
case SECONDCHOICE:
// Code
break;
}
}
and usage it as:
myFunction('String', FIRSTCHOICE);
So for instance I would make different type of alerts that output a message in different styles:
function myAlert(msg, type) {
switch(type) {
case STYLE_ONE:
alert("STYLE ONE: " + msg);
break;
case STYLE_TWO:
alert("STYLE TWO: *** " + msg + " ***");
}
}
and use it as follow:
myAlert("Hello World", STYLE_ONE);
or
myAlert("Hello World, again", STYLE_TWO);
I know that you can't make switches that does that, and I've been looking around the internet for it but with no answer on what this type is called or if it is possible. Maybe there is a workaround?
Help is much appriciated.
Best Regards, Christian
-
Well,, you could always create a global variable var MYCONSTANT = 1; var MYCONSTANT2 = 2; and then refer to them in the switch and input argsnetbrain– netbrain2011年04月29日 13:48:45 +00:00Commented Apr 29, 2011 at 13:48
-
1Or better yet... var SOME_CONSTANT_TYPE = { style_one:1, style_two:2, style_three:3 }; then call myFunction('string',SOME_CONSTANT_TYPE.style_one)netbrain– netbrain2011年04月29日 13:51:51 +00:00Commented Apr 29, 2011 at 13:51
4 Answers 4
I don't see what your specific problem is, here. Those look like regular consts, which could easily be created as global variables in javascript.
var STYLE_ONE = 1;
var STYLE_TWO = 2;
function myAlert(msg, type) {
switch(type) {
case STYLE_ONE:
alert("STYLE ONE: " + msg);
break;
case STYLE_TWO:
alert("STYLE TWO: *** " + msg + " ***");
}
}
myAlert("test", STYLE_TWO);
Comments
TRY this:
function myAlert(msg, type) {
switch(type) {
case 'STYLE_ONE':
alert("STYLE ONE: " + msg);
break;
case 'STYLE_TWO':
alert("STYLE TWO: *** " + msg + " ***");
}
}
myAlert("Hello World", 'STYLE_TWO');
Comments
what you want, is the javascript equivalent of an enum.
Basically, an enum is an integer with a name.
in javascript, this could be done as follows:
var enumObj = new Object();
enumObj.type = {help:1, about:2, quit:3}
document.write(enumObj.type.about);
// outputs : 2
Comments
var SOME_CONSTANT_TYPE = { style_one:1, style_two:2, style_three:3 };
then call
myFunction('string',SOME_CONSTANT_TYPE.style_one)
Comments
Explore related questions
See similar questions with these tags.