我希望有一个阵列,其客人没有"拒绝"作为回应。因此,Tooth Fairy被删除(不应该,她已经接受了#34;邀请)并且杰克弗罗斯特停留了(不应该,#34;他拒绝了#34;邀请)。
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);
答案 0 :(得分:2)
首先,你需要在即将到来的数组中获取人物的索引,然后使用splice根据它的索引删除该人。
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);
答案 1 :(得分:2)
您可以使用人员的姓名作为键将响应数组更改为对象。我认为管理起来有点简单。
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'
}
答案 2 :(得分:1)
那是因为它们在不同数组中列出的顺序不同。
首先你会找到#34;复活节兔子&#34;在responses
数组上,您从coming
数组中删除第一个匹配项,而不检查它是什么。在这种情况下,它对应。
然后,你发现&#34;拒绝&#34;由杰克弗罗斯特&#34;并从coming
删除第一个(新)事件,现在是#34; Tooth Fairy&#34;。
更改顺序,以便两个数组具有相同的顺序,或者以不同的方式编码以不依赖于顺序(在我看来这更好)。