繁体   English   中英

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

[英]array.splice deletes wrong value and keeps wrong value

我想与没有“下降”作为回应的来宾进行交流。 因此,从阵列中删除了Tooth Fairy(不应,她“接受”了邀请),而Jack Frost留下了(不应,他“拒绝了”邀请)。

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); 

首先,您需要获取即将到来的数组中人员的索引,然后使用拼接根据其索引删除该人员。

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

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

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

然后,通过“杰克弗罗斯特”发现“衰落”和你删除第一个(新的)发生coming ,也就是现在的“牙仙”。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM