Returning true if JavaScript array contains an element

后端 未结 4 559
心在旅途
心在旅途 2021-01-28 01:12

So far I have this code:

var isMatch = viewedUserLikedUsersArray.indexOf(logged_in_user);
    if (isMatch >=0){
      console.log(\'is match\');
    }
    els         


        
4条回答
  •  -上瘾入骨i
    2021-01-28 01:51

    At first, we have to understand, what is stored in viewedUserLikedUsersArray array.

    If there are primitives, it's ok, but if there are objects we can't use indexOf method of array, because it use strict comparison === inside, how we know, the comparison with object is going by link.

    indexOf works similar to iterating through the loop, the only way.

    In case with objects we can use find method of array MDN Array.prototype.find() or findIndex Array.prototype.findIndex();

    Also we can store users in hashMap with userId keys, and check matching by referring to the object property.

    var someUsers = {
      '#124152342': {
        ...
      },
      '#534524235': {
        ...
      },
      ...
    };
    
    ...
    
    var someUserId = '#124152342';
    
    if (someUsers[someUserId]) {
      console.log('is match');
    } else {
      console.log('no match');
    }

提交回复
热议问题