gpt4 book ai didi

javascript - 逻辑运算符始终为真?

转载 作者:行者123 更新时间:2023-12-03 03:56:14 25 4
gpt4 key购买 nike

我想要的是将当前 url 与我的 cookie 数组进行比较,该数组将包含用户访问过的所有 URL,以便比较该数组是否包含当前链接,如果不包含,它将将该新链接推送到数组,并再次使用包含新推送链接的新数组重新创建 cookie,所以我现在面临的是,每次检查唯一链接的 if 函数总是为真,我不确定问题是什么?

你们能看一下吗:

<script type="text/javascript">

function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

var url = window.location.href;
var pathname = new URL(url).pathname;
var jsonObj = [];

//jsonObj.push("test");

var x = readCookie('vid_cookies');
if (x) {
var res = x.split(",");
console.log(res);
for (var i = 0; i < res.length; i++) {
if (pathname != res[i]) {
alert("IS NOT EQUAL");
//res.push(pathname);
//var joinedArray = res.join(",");
//console.log(joinedArray);
//createCookie('vid_cookies',joinedArray,7);
//var z = readCookie('vid_cookies');
//console.log(z)
}
}
} else {
jsonObj.push(pathname);
createCookie('vid_cookies',jsonObj,7);
}


//alert(jsonObj);

</script>

这是数组:

["/evercookie-master/yahoo.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html", "/evercookie-master/facebook.html"]

最佳答案

逻辑不正确。如果您只想将尚不存在的值添加到数组中,则必须在添加之前检查所有元素。

在您的代码中,一旦任何元素不匹配,您就会添加该值。当然,情况总是如此,因为在 n 个元素中,n - 1 将不匹配。

一种方法是使用Array#every:

if (res.every(x => x !== pathname)) {
// add to array and set cookie
}

或者,您可以将数组转换为Set,始终添加值并设置 cookie。 Set 将自动对值进行重复数据删除:

var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);

关于javascript - 逻辑运算符始终为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com