如何更好地编写以下Javascript代码段?

时间:2015-02-22 12:16:56

标签: javascript

我正在处理需要设置的大量变量。我只使用5个变量来说明我的问题。

这是js片段:

//Make sure everything is empty
var BCode = '', 
    CID = '',
    Journey = '',
    CentreID = '',
    YearOfBirth = '';

//Get the data getVar is just a global function to get data, the data can be "falsy" e.g. "null" "empty" - this is connected to my second question - please see the next block of code.

BCode = getVar('bcode');
CID = getVar('cid');
Journey = getVar('journey');
CentreID = getVar('centreID');
YearOfBirth = getVar('YOB');

//Currently I am not checking if the "BCode", "CentreID" or any other data is "falsy" e.g. "null, empty" etc.

b1 = Bcode
b2 = CID + CentreID
b3 = Journey
b4 = CentreID
b5 = YearOfBirth

我想知道是否有更好的方法来重新编写JavaScript代码段,因为我有100个必须如上设置的变量?

如果我的变量BCode = getVar('bcode');返回" falsy"价值然后我想知道如何完全省略这个变量 - 如果检查值是否为空,我不想写100。基本上

如果BCode is "empty" or "null"那么我不希望代码b1 = Bcode完全被执行 - 好像它从未出现过一样。同样适用于b2,b3等。有没有办法处理上面的100多个变量设置/获取方案,其中值可能是假的?

非常感谢。

1 个答案:

答案 0 :(得分:1)

你应该使用.forEach,以及一个键值对的对象,表示哪个数据可以进入哪个变量。除非您处于全局范围内,否则无法直接定义变量,即便如此,它仍然不是那种类型的定义,因此请改用对象。

Object.keys在不同浏览器上的行为可能不同,这意味着键的顺序可能与您定义的不同。如果订单很重要(它不应该),那么您需要手动编写keys`数组,但是当您设置变量时,顺序可能并不重要。

var variableNames = {
    BCode: 'bcode',
    CID: 'cid',
    Journey: 'journey',
    CentreID: 'centreID',
    YearOfBirth: 'YOB',
}, keys = Object.keys(variableNames),
// This is the object we'll store the "variables" in
Var = {};

keys.forEach(function(dataName, key){
    var data = getVar(dataName);
    // If the data is not falsy (evaluates to true) thad add it to Var
    if (!!data) Var[key] = data;
});

// All of your variables are now accessible from Var
Var.BCode;

// You can also use the bracket syntax for keys that have spaces, dots or other characters that you can't write directly
Var['Variable Name'];

如果您 确实 想要使用常规变量之类的值,并且您正在全局范围内工作(即不在函数内部,并且可以访问所有变量例如,从浏览器的JS控制台),如果您在上面的代码中使用window而不是Var,则可以直接设置变量:

var variableNames = {
    BCode: 'bcode',
    CID: 'cid',
    Journey: 'journey',
    CentreID: 'centreID',
    YearOfBirth: 'YOB',
}, keys = Object.keys(variableNames);

keys.forEach(function(dataName, key){
    var data = getVar(dataName);
    if (!!data) window[key] = data;
});

BCode;
window['Variable Name'];