如何设置if语句来更改变量

时间:2019-05-29 20:17:47

标签: javascript

如果没有可用值,我正在尝试将javascript中的变量更改为默认值

// Parse the URL
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');

我正在使用一些JavaScript通过pardot形式从网址传递utm变量。我想将默认值设置为Organic作为值,然后将其更改为网址中提供的变量(如果可用)

1 个答案:

答案 0 :(得分:1)

您可以将默认值作为参数传递给函数,然后在条件运算符而不是""中返回它:

function getParameterByName(name, default) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? default : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source', source);
var medium = getParameterByName('utm_medium', medium);
var campaign = getParameterByName('utm_campaign', campaign);

另一种选择是使用||运算符在分配中应用默认值:

/ Give the URL parameters variable names
var source = 'organic';
var medium = 'organic';
var campaign = 'organic';

// Give the URL parameters variable names
var source = getParameterByName('utm_source') || source;
var medium = getParameterByName('utm_medium') || medium;
var campaign = getParameterByName('utm_campaign') || campaign;