假设我们有一个对象数组,其中包含有关某些电影的数据,例如:
const arr = [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, {id: "3", name: "X-Men", type: "action"}, {id: "4", name: "Ordinary People", type: "drama"}, {id: "5", name: "Billy Elliot", type: "drama"}, {id: "6", name: "Toy Story", type: "children"} ];
我们需要编写一个JavaScript函数,该函数将一个数组作为第一个参数,并将id字符串作为第二个参数。然后,我们的函数应按该ID搜索对象,如果数组包含该对象,则应将其从数组中删除。
为此的代码将是-
const arr = [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, {id: "3", name: "X-Men", type: "action"}, {id: "4", name: "Ordinary People", type: "drama"}, {id: "5", name: "Billy Elliot", type: "drama"}, {id: "6", name: "Toy Story", type: "children"} ]; const removeById = (arr, id) => { const requiredIndex = arr.findIndex(el => { return el.id === String(id); }); if(requiredIndex === -1){ return false; }; return !!arr.splice(requiredIndex, 1); }; removeById(arr, 5); console.log(arr);
输出结果
控制台中的输出将是-
[ { id: '1', name: 'Snatch', type: 'crime' }, { id: '2', name: 'Witches of Eastwick', type: 'comedy' }, { id: '3', name: 'X-Men', type: 'action' }, { id: '4', name: 'Ordinary People', type: 'drama' }, { id: '6', name: 'Toy Story', type: 'children' } ]