Simple requirement is to delete elements that do not meet the conditions in the array.
The initial implementation, foreach
loop, was found to be wrong.
// 如果学科存在id if (discipline.id) { // foreach类别 angular.forEach(result, function(value, key) { // 如果该类别有对应学科(考虑到“请选择的情况下”会报从undefined上获取id) // 并且该学科类别id不等于传入学科id if (value.discipline && !angular.equals(value.discipline.id, discipline.id)) { // 移除不符合要求的元素 result.splice(key, 1); } }); }
Every time you delete, it is deleted based on key
, but after deletion, the length of the array will change, causing it to be deleted based on key
next time. Go to delete and find that the length has changed and the position of the element we want to delete has also changed.
In Java
, we use the iterator
method to get its iterator object and then modify it.
// 如果学科存在id if (discipline.id) { /** * 数组过滤 * 接收一个函数,根据该函数返回为true/false * 决定该元素保留还是删除 */ result = result.filter(function(value) { // 兼容请选择项,默认保留 if (!value.discipline) { return true; } // 保留器具类别的学科id与当前学科id相同的项 return angular.equals(value.discipline.id, discipline.id); }); }
Related articles:
Problems that occur when the for loop deletes the contents of array elements in JavaScript
The above is the detailed content of js tutorial - Array loop deletion error implementation and solution. For more information, please follow other related articles on the PHP Chinese website!