簡體   English   中英

javascript 未從數組中刪除未定義的對象

[英]javascript not removing undefined objects from array

我有一個使用 JS 的頁面內文本搜索,這里是:

$.fn.eoTextSearch = function(pat) {
    var out = []
    var textNodes = function(n) {
        if (!window['Node']) {
            window.Node = new Object();
            Node.ELEMENT_NODE = 1;
            Node.ATTRIBUTE_NODE = 2;
            Node.TEXT_NODE = 3;
            Node.CDATA_SECTION_NODE = 4;
            Node.ENTITY_REFERENCE_NODE = 5;
            Node.ENTITY_NODE = 6;
            Node.PROCESSING_INSTRUCTION_NODE = 7;
            Node.COMMENT_NODE = 8;
            Node.DOCUMENT_NODE = 9;
            Node.DOCUMENT_TYPE_NODE = 10;
            Node.DOCUMENT_FRAGMENT_NODE = 11;
            Node.NOTATION_NODE = 12;
        }
        if (n.nodeType == Node.TEXT_NODE) {
            var t = typeof pat == 'string' ?
            n.nodeValue.indexOf(pat) != -1 :
            pat.test(n.nodeValue);
            if (t) {
                out.push(n.parentNode)
            }
        }
        else {
            $.each(n.childNodes, function(a, b) {
                textNodes(b)
            })
        }
    }
    this.each(function() {
        textNodes(this)
    })
    return out
};

而且我有能力隱藏表格中的列和行。 當我提交搜索並獲得突出顯示的結果時,在這種情況下,找到的文本節點的數組長度將為 6,但頁面上只有 3 個突出顯示。 當您將 output 陣列到控制台時,您會得到以下信息:

所以你得到了我期待的 3 個標簽,但是你看到數組實際上是由一個[span,undefined,span,undefined,undefined,span]組成的。 因此給了我6的長度。

<span>
<span>
<span>
[span, undefined, span, undefined, undefined, span]

我不知道為什么當我檢查它們時它沒有去除所有未定義的文本節點。 這是我為 function 准備的。

performTextSearch = function(currentObj){
    if($.trim(currentObj.val()).length > 0){
        var n = $("body").eoTextSearch($.trim(currentObj.val())),
            recordTitle = "matches",
            arrayRecheck = new Array(),
            genericElemArray = new Array()
        if(n.length == 1){
            recordTitle = "match"
        }

        //check to see if we need to do a recount on the array length. 
        //if it's more than 0, then they're doing a compare and we need to strip out all of the text nodes that don't have a visible parent.
        if($(".rows:checked").length > 0){
            $.each(n,function(i,currElem){
                if($(currElem).length != 0 && typeof currElem != 'undefined'){
                    if($(currElem).closest("tr").is(":visible") || $(currElem).is(":visible")){
                        //remove the element from the array
                        console.log(currElem)
                        arrayRecheck[i] = currElem
                    }
                }
            })
        }
        if(arrayRecheck.length > 0){
            genericElemArray.push(arrayRecheck)
            console.log(arrayRecheck)
        }
        else{
            genericElemArray.push(n)    
        }
        genericElemArray = genericElemArray[0]
        $("#recordCount").text(genericElemArray.length + " " +recordTitle)
        $(".searchResults").show()
        for(var i = 0; i < genericElemArray.length; ++i){ 
            void($(genericElemArray[i]).addClass("yellowBkgd").addClass("highLighted"))
        }   
    }
    else{
        $(".highLighted").css("background","none")  
    }           
}

如果您查看下面的代碼“//check to see if we need to do a recount on the array length.”,您將看到我根據顯示剝離文本節點的位置以及是否object 已定義。 我正在檢查長度而不是 undefined,因為 typeof == undefined 由於某種原因根本不起作用。 顯然,事情仍在溜走。

知道為什么我仍然在數組中得到未定義的對象嗎?

我為這么大的帖子道歉!

提前致謝

我已經修改了您的eoTextSearch() function 以刪除對全局變量的依賴以換取閉包:

$.fn.extend({
  // helper function
  // recurses into a DOM object and calls a custom function for every descendant
  eachDescendant: function (callback) {
    for (var i=0, j=this.length; i<j; i++) {
      callback.call(this[i]);
      $.fn.eachDescendant.call(this[i].childNodes, callback);
    }
    return this;
  },
  // your text search function, revised
  eoTextSearch: function () {
    var text = document.createTextNode("test").textContent 
               ? "textContent" : "innerText";
    // the "matches" function uses an out param instead of a return value
    var matches = function (pat, outArray) {
      var isRe = typeof pat.test == "function";
      return function() {
        if (this.nodeType != 3) return; // ...text nodes only
        if (isRe && pat.test(this[text]) || this[text].indexOf(pat) > -1) {
          outArray.push(this.parentNode);
        }
      }
    };
    // this is the function that will *actually* become eoTextSearch()
    return function (stringOrPattern) {
      var result = $(); // start with an empty jQuery object
      this.eachDescendant( matches(stringOrPattern, result) );
      return result;
    }
  }()  // <- instant calling is important here
});

然后你可以做這樣的事情:

$("body").eoTextSearch("foo").filter(function () {
  return $(this).closest("tr").is(":visible");
});

從搜索結果中刪除不需要的元素。 不需要“重新計算數組長度” 或者你直接使用each()並決定做什么。

我無法完全理解您的代碼,但最可能的問題是您正在從數組中刪除項目,但之后沒有縮小數組。 簡單地刪除項目將返回“未定義”,並且不會折疊數組。

我建議您執行以下操作之一:

  1. 將數組復制到新數組,但只復制那些未定義的項

  2. 僅使用那些未定義的數組項。

我希望這能有所幫助。

在另一篇文章中找到了答案。

從 Javascript 中的數組中刪除空元素

最終使用答案的第二個選項,它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM