简体   繁体   中英

jQuery if cookie exists in array

I originally used the following jQuery statement to see if my cookie existed:

if (document.cookie.indexOf('cookie-foo') >= 0) {
    $("my-div").hide();
}

I now need to include multiple if statements, which I thought I'd tidy as an array:

var hidenfoo = ['cookie-foo', 'cookie-foo-two', 'cookie-foo-three'];
if (document.cookie.indexOf(hidenfoo) >= 0) {
    $("my-div").hide();
}

Unfortunately, this doesn't work. I'm not getting any syntax errors, the statement simply doesn't resolve as true.

You need to test each array element separately, not the whole array. You can use the some() method to perform a test on each element and return true if any of them are true.

if (hidenfoo.some(cookie => document.cookie.includes(cookie))) {
    $("my-div").hide();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM