Home > Web Front-end > JS Tutorial > body text

js tutorial - Array loop deletion error implementation and solution

php是最好的语言
Release: 2018-08-06 15:59:07
Original
2345 people have browsed it

Problem Description

Simple requirement is to delete elements that do not meet the conditions in the array.

Wrong implementation

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);
        }
    });
}
Copy after login

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.

Solution

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);
    });
}
Copy after login

Related articles:

Problems that occur when the for loop deletes the contents of array elements in JavaScript

One about arrays Loop problem

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template