array.splice 删除错误值并保留错误值

array.splice deletes wrong value and keeps wrong value

我想要一个没有 "decline" 作为回应的客人的数组。因此,Tooth Fairy 从数组中删除(不应该,她 "accepted" 邀请)而 Jack Frost 保留(不应该,他 "declined" 邀请)。

function getAttendees(peopleInvited, responses){
    var coming=peopleInvited;
  responses.map(function(cell){
      if (cell.response=='declined') {
        coming.splice(0,1);
         }         
      });
    return coming;  
}

var people = ['Easter Bunny', 'Tooth Fairy', 'Frosty the Snowman', 
              'Jack Frost', 'Cupid', 'Father Time'];
var responses = [ 
     {name: 'Easter Bunny', response: 'declined'}, 
     {name: 'Jack Frost', response: 'declined'}, 
     {name: 'Tooth Fairy', response: 'accepted'} 
   ];

getAttendees(people, responses); 

这是因为它们在不同数组中的排列顺序不同。

首先在 responses 数组中找到 "Easter Bunny",然后从 coming 数组中删除第一个匹配项而不检查它是什么。在这种情况下,它对应。

然后,您通过 "Jack Frost" 找到 "decline" 并从 coming 中删除第一个(新的)匹配项,现在是 "Tooth Fairy"。

要么更改顺序以使两个数组具有相同的顺序,要么对其进行不同的编码以不依赖于顺序(我认为这样更好)。

首先你需要得到即将到来的数组中的人的索引,然后根据它的索引使用拼接来删除那个人。

function getAttendees(peopleInvited, responses){
  var coming=peopleInvited;
  responses.map(function(cell){
    if (cell.response=='declined') {
      var index = coming.indexOf(cell.name);
      coming.splice(index, 1);
    }         
  });
  return coming;  
}

var people = ['Easter Bunny', 'Tooth Fairy', 'Frosty the Snowman', 
     'Jack Frost', 'Cupid', 'Father Time'];
var responses = [ 
  {name: 'Easter Bunny', response: 'declined'}, 
  {name: 'Jack Frost', response: 'declined'}, 
  {name: 'Tooth Fairy', response: 'accepted'} 
];

getAttendees(people, responses); 

您可以将响应数组改为使用人名作为键的对象。我认为这更容易管理。

function getAttendees(people, responses) {
    for (var i = 0, l = people.length, out = []; i < l; i++) {
        var response = responses[people[i]];
        if (!response || response && response === 'accepted') {
            out.push(people[i]);
        }
    }
    return out;
}

var people = ['Easter Bunny', 'Tooth Fairy', 'Frosty the Snowman',
    'Jack Frost', 'Cupid', 'Father Time'];

var responses = {
    'Easter Bunny': 'declined',
    'Jack Frost': 'declined',
    'Tooth Fairy': 'accepted'
}

DEMO