如何使此 JS 代码仅在语句为真时执行?设置饼干

How to make this JS code executed only if statement is true? Set cookies

请帮我在 js 中找到一个合适的解决方案:

1) 我有一个来自 referrer 的 URL,其中包含两个变量

2) 我必须捕获 pdidpuid 变量形式 URL 并设置名称为 [=46= 的 cookie ] 和 POKUPON_UID 及其值

3) 如果URL 不包含此变量,cookie 设置为undefined 的主要问题。我需要你帮助我修改 IF 语句。代码应该只执行一次,如果 URL 中的变量存在...

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 
if($POKUPON_DID != emty){
    
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}

非常感谢您!

您需要检查是否有未定义的阅读内容: How to check for "undefined" in JavaScript?

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 console.log($POKUPON_DID);
 console.log($POKUPON_UID);

if(typeof $POKUPON_DID != 'undefined'){
setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}