开发者

Explode a string into a hashmap for searching?

开发者 https://www.devze.com 2023-01-21 07:28 出处:网络
开发者_运维百科I have a string like this being returned from my backend: \"1,2,3,4,5,6\" I have a large array locally and want to display only those items not in this list, so I was thinking of exp
开发者_运维百科

I have a string like this being returned from my backend:

"1,2,3,4,5,6"

I have a large array locally and want to display only those items not in this list, so I was thinking of exploding this string into an array but how can I search efficiently? As far as I know there are no hashmaps in JS so how does one do this? I just need to check for key existence.


All Javascript objects are also hash tables that can store string or numeric keys:

var x = {};
x["foo"] = 1;
if("foo" in x) { alert("hello!"); }
if("bar" in x) { alert("should never see this"); }


"1,2,3,4,5,6".split(",").some(function(letter) { 
  return letter === '2' 
});

Warning: Might not work in IE (or other crappy browser)

Cross browser version (that relies on native code for performance):

var arr = "1,2,3,4,5,6".split(",");
if(arr.some)
{
  arr.some(function(letter) { 
    return letter === '2' 
  });
}
else
{
  for(var i  = 0 ; i < arr.length ; i++ )
  {
      if(arr[i] === '2') return true;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号