Returning true if JavaScript array contains an element

后端 未结 4 552
心在旅途
心在旅途 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条回答
  •  失恋的感觉
    2021-01-28 01:41

    Probably going to get blasted for some reason but hey, why not!

    function findMatch(arr, user) {
        var i = 0, count = arr.length, matchFound = false;
    
        for(; i < count; i++) {
            if (arr[i] === user) {
                matchFound = true;
                break;
            }
        }
    
        return matchFound;
    }
    
     var isMatch = findMatch(viewedUserLikedUsersArray, logged_in_user); // etc.
    

    An alternative could also be to use includes()

    var isMatch = viewedUserLikedUsersArray.includes(logged_in_user); // returns true/false
    

提交回复
热议问题