[英]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'
}
這是因為它們在不同數組中列出的順序是不同的。
首先,您在responses
數組上找到“ Easter Bunny”,然后從coming
數組中刪除第一個匹配項,而不檢查它是什么。 在這種情況下,它對應。
然后,通過“傑克弗羅斯特”發現“衰落”和你刪除第一個(新的)發生coming
,也就是現在的“牙仙”。
要么更改順序,以使兩個數組都具有相同的順序,要么以不同的方式對其進行編碼以不依賴順序(我認為更好)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.