Returning true if JavaScript array contains an element

后端 未结 4 557
心在旅途
心在旅途 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:27

    The One and Only ChemistryBlob answer with Array.prototype

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

提交回复
热议问题