Logical Operator Always Stays True?
What I want is to compare current url with my cookie array which would contain all the URL's a user has visited so it would compare that whether the array contains the current link
Solution 1:
The logic is not correct. If you want to add a value to an array only if it doesn't exist yet, you have to check all elements before you add it.
In your code you are adding the value as soon as any of the element doesn't match. That will always be the case of course because out n
elements, n - 1
will not match.
One way to do it would be to use Array#every
:
if (res.every(x => x !== pathname)) {
// add to array and set cookie
}
Alternatively you could convert the array to a Set
, always add the value and set the cookie. The Set
will automatically dedupe the values:
var res = new Set(x.split(","));
res.add(pathname);
res = Array.from(res);
Post a Comment for "Logical Operator Always Stays True?"