복붙노트

[JQUERY] 루프에서 스플 라이스와 어레이로부터 항목 삭제 [중복]

JQUERY

루프에서 스플 라이스와 어레이로부터 항목 삭제 [중복]

해결법


  1. 1.당신은 다음과 같은 뭔가, 루프 뒤쪽을 할 수 있습니다

    당신은 다음과 같은 뭔가, 루프 뒤쪽을 할 수 있습니다

    var searchInput, i;
    
    searchInput = ["this", "is", "a", "test"];
    i = searchInput.length;
    while (i--) {
        if (searchInput[i].length < 4) {
            searchInput.splice(i, 1);
        }
    }
    

    DEMO : http://jsfiddle.net/KXMeR/

    이것은 배열을 통해 점진적으로 반복하기 때문에 당신이 그것을 스플 라이스 때 항목이 "이동"이며, 일부의 반복을 건너 뛰는 끝날 수 있도록, 배열, 장소 수정이다. 당신이 방향을 당신이있는 거 접합에서 반복되지 있기 때문에 (잠시 심지어 루프로) 뒤쪽을 반복하는 것은이 문제를 해결합니다.

    동시에, 대신 장소에서 하나를 수정하는 새로운 배열을 생성하는 것이 더 빠르다. 다음은 그 예이다 :

    var searchInput, newSearchInput, i, j, cur;
    
    searchInput = ["this", "is", "a", "test"];
    newSearchInput = [];
    for (i = 0, j = searchInput.length; i < j; i++) {
        cur = searchInput[i];
        if (cur.length > 3) {
            newSearchInput.push(cur);
        }
    }
    

    어디 newSearchInput에만 유효 길이 항목이 포함되며, 당신은 여전히 ​​searchInput의 원래 항목이있다.

    DEMO : http://jsfiddle.net/RYAx2/

    필터 : 상기 제 2 용액에 부가 유사한 Array.prototype으로 새로운 방법은 더 잘 처리 할 수있다. 다음은 그 예이다 :

    var searchInput, newSearchInput;
    
    searchInput = ["this", "is", "a", "test"];
    newSearchInput = searchInput.filter(function (value, index, array) {
        return (value.length > 3);
    });
    

    DEMO : http://jsfiddle.net/qky7D/

    참고 :


  2. 2.

    var myArr = [0,1,2,3,4,5,6];
    

    문제 설명:

    myArr.splice(2,1);
    
      \\ [0, 1, 3, 4, 5, 6];
    

    이제 2 위치와 길이 3 개 이동은 문제점을 생성한다 (1)에 의해 감소된다.

    해결 방법 : 접합 간단한 해결책은 반대 방향으로 반복하는 일 것입니다.

    var i = myArr.length;
    while (i--) {
        // do your stuff
    }
    

  3. 3.당신이 lodash 라이브러리가 설치되어있는 경우, 그들은 당신이 고려하는 것이 좋습니다 달콤한 보석이있다.

    당신이 lodash 라이브러리가 설치되어있는 경우, 그들은 당신이 고려하는 것이 좋습니다 달콤한 보석이있다.

    함수는 _.forEachRight이다 (오른쪽에서 왼쪽으로 컬렉션의 요소를 반복)

    다음은 예이다.

    var searchInput = ["this", "is", "a", "test"];
    
    _.forEachRight(searchInput, function(value, key) {
    
        if (value.length < 4) {
            searchInput.splice(key, 1);
        }
    });
    

  4. 4.또한 배열을 필터링 $ .grep 기능을 사용할 수 있습니다 :

    또한 배열을 필터링 $ .grep 기능을 사용할 수 있습니다 :

    var timer, searchInput;
    $('#searchFAQ').keyup(function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
            searchInput = $('#searchFAQ').val().split(/\s+/g); // match is okay too
            searchInput = $.grep(searchInput, function(el) {
                return el.length >= 4;
            });
            console.log(searchInput);
        }, 500);
    });
    

    http://jsfiddle.net/dfsq/4Wdp9/


  5. 5.또 다른 방법은 배열이 다음 요소 아래로 이동됩니다 때 너무 생략하지 않습니다, 당신은 배열 (x--)에서 슬라이스마다 인덱스를 감소하는 것입니다.

    또 다른 방법은 배열이 다음 요소 아래로 이동됩니다 때 너무 생략하지 않습니다, 당신은 배열 (x--)에서 슬라이스마다 인덱스를 감소하는 것입니다.

    var searchInput;
    
    searchInput = ["this", "is", "a", "test"];
    for (var x = 0; x < searchInput.length; x++) {
        if (searchInput[x].length < 4) {
            searchInput.splice(x--, 1);
        }
    }
    
    console.log(searchInput);
    

    DEMO : https://jsfiddle.net/alinaeem229/n2kq3690/1/

  6. from https://stackoverflow.com/questions/16217333/remove-items-from-array-with-splice-in-for-loop by cc-by-sa and MIT license