轻松将多个变量设置为false或true

时间:2012-01-09 11:49:28

标签: javascript

我在Javascript中定义了多个布尔值:

在切换时我想将它们设置为false或true。

var categoryAdvertising = false;
var categoryInformArtation = false;
var categoryACA = false;
var categoryEntertainment = false;
var categoryInfluencing = false;
var categoryICE = false;
var categoryCommunication = false;
var categoryParticipation = false;

设置这些变量的最佳方法是什么?使用数组?

提前完成

3 个答案:

答案 0 :(得分:6)

只需使用一个对象:

var category = {
    Advertising: false,
    InformArtation: false,
    ACA: false,
    Entertainment: false,
    Influencing: false,
    ICE: false,
    Communication: false,
    Participation: false
};

for( var key in category ) {
    category[key] = false;
}

访问对象键:

alert( category.Advertising );

答案 1 :(得分:2)

绝对是的。您应该使用Array,或者如果您需要明确的标识符,请使用Object

var config = {
    categoryAdvertising: false,
    categoryInformArtation: false,
    categoryACA : false
    // etc
};

然后切换所有

Object.keys( config ).forEach(function( opt ) {
    config[ opt ] = true; // or false
});

免责声明:此答案包含使用旧版浏览器中不存在的功能的代码,以下链接是有关如何在旧版浏览器中模拟这些功能的建议:

Object#keys

甚至更好,总是使用ES5shim,如:

https://github.com/kriskowal/es5-shim

答案 2 :(得分:0)

如果您确实需要定期将它们全部设置为truefalse,那么您会想知道是否真的需要这么多吗?

但如果你这样做,请使用一个功能。在函数中,您可以使用堆叠赋值,例如:

function setVars(value) {
    categoryAdvertising =
        categoryInformArtation =
            categoryACA =
                categoryEntertainment =
                    categoryInfluencing =
                        categoryICE =
                            categoryCommunication =
                                categoryParticipation =
                                    value;
}

我打算给你第二个选项,但Esailija got there ahead of me(+1)。