$ .inArray () return not expected

1

Array cookiesplit contain exactly this content:

_utma=246244038.1458519878.1422527074.1423248864.1423253252.8,    
__utmz=246244038.1422527074.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none), 
_ga=GA1.2.1458519878.1422527074, newsletter=ok, tracking202subid=30883, 
tracking202pci=6308836, _gat=1

This above is an array, cookiesplit was built like this below:

cookie = document.cookie;
cookiesplit = [];

cookiesplit = cookie.split(";");

Well, you see, at some index of this array we have the value newsletter = ok , I checked this by doing a $(cookiesplit).each(function(x){} .

The problem is that you are returning -1 when I check if they contain this value newsletter = ok , see the code that does this check:

res = $.inArray("newsletter=ok", cookiesplit); // res retorna -1

In my understanding, it was to return the value of the newsletter = ok value, since it exists, if it did not exist it would return -1, but as I showed above, p>     

asked by anonymous 07.02.2015 / 03:39

1 answer

3

You are using semicolon as a delimiter ( ; ), but the correct one is a comma ( , ).

var cookiesplit = array.split(',');

The method .InArray() searches for an exact value in array , is returned -1 because there is a blank at the beginning of the value. Therefore to find this value you should use " newsletter=ok" .

var array ="_utma=246244038.1458519878.1422527074.1423248864.1423253252.8, 
  __utmz=246244038.1422527074.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none),
  _ga=GA1.2.1458519878.1422527074, newsletter=ok, tracking202subid=30883,
  tracking202pci=6308836, _gat=1";

var cookiesplit = array.split(',');
var res = $.inArray(" newsletter=ok", cookiesplit);

alert(res); // 3

Fiddle

If you prefer, something more elegant:

var cookiesplit = $.map(array.split(','), $.trim);
var res = $.inArray("newsletter=ok", cookiesplit);

alert(res); // 3

Fiddle

    
07.02.2015 / 04:33