【问题标题】:JavaScript - prevent push of certain element into an array if condition is trueJavaScript - 如果条件为真,防止将某些元素推入数组
【发布时间】:2016-09-03 08:09:32
【问题描述】:

所以我有这个系统可以遍历一组用户,如果他们的类型偏好与我的匹配,那么他们就会被推送到一系列潜在匹配中。但是我希望它不能与自己匹配(即具有相同用户 ID 的用户,在本例中为“324”),但我希望将其余匹配推入数组中。

var me = {meUserid: 324, meGenre: 'rock'};

var users = {
    user1: {userid: 276, userGenre: 'rock'},
    user2: {userid: 335, userGenre: 'jazz'},
    user3: {userid: 324, userGenre: 'rock'}, //Same userid and genre
    user4: {userid: 603, userGenre: 'rock'},
    user5: {userid: 502, userGenre: 'country'},
};

// Users array
var userProfile = [];

// Populate users array
for(var key in users) {
    userProfile.push(users[key]);
}

var potentialMatches = [];

for(var i = 0; i < userProfile.length; i++){

    // If genre matches that of another user's genre preference, push these compatible users into matches array
    if(userProfile[i].userGenre == me.meGenre){

        potentialMatches.push(userProfile[i]);
    }
}

console.log(potentialMatches);

我知道这将是一个 if 语句,类似于:

if(meUserid == userProfile[i].userid){
   //Do something
}

但我不确定如何做 if 语句,有什么想法吗?

结果应该类似于:

potentialMatches = [{user1: {userid: 276, userGenre: 'rock'}}, {user4: {userid: 603, userGenre: 'rock'}}]

谢谢!

【问题讨论】:

    标签: javascript loops if-statement push


    【解决方案1】:

    只需将其添加到 if 语句中

    for (var i = 0; i < userProfile.length; i++) {
      if (userProfile[i].userGenre == me.meGenre && userProfile[i].userid != me.meUserid) {
         potentialMatches.push(userProfile[i]);
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用Array#filter 并使用Array#map 构建数组。

      var me = { meUserid: 324, meGenre: 'rock' },
          users = { user1: { userid: 276, userGenre: 'rock' }, user2: { userid: 335, userGenre: 'jazz' }, user3: { userid: 324, userGenre: 'rock' }, user5: { userid: 502, userGenre: 'country' } },
          result = Object.keys(users).filter(function (k) {
              return users[k].userid === me.meUserid && users[k].userGenre === me.meGenre;
          }).map(function (k) { return users[k] });
      
      document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

      【讨论】:

        【解决方案3】:

        只需在当前循环中添加这个:

        if(userProfile[i].userid != me.meUserid){
            potentialMatches.push(userProfile[i]);
        }
        

        或者您也可以将它与另一个 if 循环一起添加:

        if (userProfile[i].userGenre == me.meGenre && userProfile[i].userid != me.meUserid) {
             potentialMatches.push(userProfile[i]);
           }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-06
          • 2020-05-07
          • 1970-01-01
          • 1970-01-01
          • 2020-07-10
          • 2019-03-10
          相关资源
          最近更新 更多