简体   繁体   English

javascript - 检查cookie值是否在数组中

[英]javascript - check if cookie value is in an array

Im learning javascript right now, so this might be a really newb question! 我现在正在学习javascript,所以这可能是一个非常新的问题! I googled it, but didnt found what I was looking for, maybe I just didnt googled the right thing, but yeah...Oh im not using any plug-ins for cookies. 我用谷歌搜索,但没有找到我想要的东西,也许我只是没有用Google搜索正确的东西,但是是的...哦,我没有使用任何插件的饼干。

I have a cookie named "country", the value is the user's country code, like US, CA, UK, AU or FR... I want to display a block of content only if the country is, let's say DE, ES, AT, IT or NL. 我有一个名为“country”的cookie,值是用户的国家代码,如US,CA,UK,AU或FR ...我想只显示一个内容块,如果国家是,让我们说DE,ES, AT,IT或NL。

The logic of what im looking for: if cookie "country" exist and country == one of the country in my array... 我正在寻找的逻辑:如果cookie“country”存在而country = =我的数组中的一个国家...

Im thinking about something like... But that is obviously too simple and not working :) 我想的是......但这显然太简单了,不能正常工作:)

var countryArray = new Array["DE", "ES", "AT", "IT", "NL"];

if( $.cookie('country') && $.cookie('country') == countryArray ) { alert("working"); }

You could use indexOf for new browsers: 您可以将indexOf用于新浏览器:

countryArray.indexOf($.cookie('country')) > -1

Also , instead of 而且,而不是

 countryArray = new Array["DE", "ES", "AT", "IT", "NL"];

you need to write: 你需要写:

 countryArray = ["DE", "ES", "AT", "IT", "NL"];

UPDATE: For old browsers include this script in your js : 更新:对于旧浏览器,在js包含此脚本:

 Array.prototype.indexOf = Array.prototype.indexOf || function( value, startIndex ){
     var i = startIndex || 0;
     for(; i < this.length; ++i){
         if( value === this[i] ){
             return i;
         }          
     }
     return -1;
 }

have an associative array instead. 有一个关联数组。

var countryArray = [];

countryArray["DE"]=true;
countryArray["ES"]=true;
etc.

if( $.cookie('country') && countryArray[$.cookie('country')] )
 { alert("working"); }

Will work in all browsers.. 将适用于所有浏览器..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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