开发者

JavaScript: A special variable/argument?

开发者 https://www.devze.com 2023-03-01 08:24 出处:网络
I\'ve been looking for a special argument and/or variable that can do this i.e.: function myFunction(arg1, arg2) {

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 S开发者_运维技巧TYLE_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


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);

Example


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');


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


var SOME_CONSTANT_TYPE = { style_one:1, style_two:2, style_three:3 }; 

then call

myFunction('string',SOME_CONSTANT_TYPE.style_one)
0

精彩评论

暂无评论...
验证码 换一张
取 消