$. inArray() return not expected

Asked

Viewed 60 times

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 this way below:

cookie = document.cookie;
cookiesplit = [];

cookiesplit = cookie.split(";");

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

The problem is it’s returning -1 when I check whether they contain this value newsletter=ok, see the code that makes this check:

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

In my understanding, it was to return the value index newsletter=ok, for it exists, if it did not exist it would return -1, but as shown above, the value exists..

1 answer

3


You are using Semicolon as delimiter(;), but what is right is a comma(,).

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

The method .InArray() search for an exact value in a array, is returned -1 because there is a white space 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

  • In fact the only problem you noticed and when applying solved, was the space at the beginning of newsletter=ok, I was looking without space.

  • I liked your suggestion to use Trim to delete the spaces, thanks, solved!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.