簡體   English   中英

從數組中刪除未定義的元素

[英]Remove undefined elements from array

我有一個表,我拉數據並將其添加到數組數組。 問題是如果其中一個表格單元格為空,則它在數組中顯示為“未定義”。 如果使用.pop(),我嘗試使用if,如果最后一個元素是未定義的,則應刪除該元素。 我仍然得到未定義的元素。 這是我的代碼和現場演示

HTML:

<table id="contactlisttable">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Phone</th>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Joey</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone"></td>
    </tr>
    <tr>
        <td class="contactlist contactlistlastfirst">Anthony</td>
        <td class="contactlist contactlisttitle">webdesigner</td>
        <td class="contactlist contactlistphone">5555555</td>
    </tr>
</table> 


JavaScript:

 //IE9+ compatable solution $(function(){ var results = [], row; $('#contactlisttable').find('th, td').each(function(){ if(!this.previousElementSibling){ //New Row? row = []; results.push(row); if($(this) === 'undefined'){//Remove undefined elements row.pop(); } } row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not) }); console.log(results); }); 

jsFiddle Demo

而不是做條件語句,只需利用您的HTML結構。 首先按表行選擇,然后迭代子tdth元素。 您還可以利用jQuery的text而不是進行特征檢測。 jQuery的文本會更可靠。

var results = [];
$('#contactlisttable tr').each(function(){
 var row = [];
 $(this).find('td,th').each(function(){
     row.push($(this).text());
 });
 results.push(row);
});
console.log(results);

如果它不匹配,而不是推動和彈出,不要先推入。

從您的jsfiddle更新:

//IE9+ compatable solution
$(function(){
    var results = [], row; 
    $('#contactlisttable').find('th, td').each(function(){
        if(!this.previousElementSibling && typeof(this) != 'undefined'){ //New Row?
            row = []; 
            results.push(row); 
        }
        row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)       
    }); 
    console.log(results); 
}); 

您還可以避免以這種方式添加未定義(或實際為空)的元素:

$('#contactlisttable').find('th, td').each(function(){
    if(!this.previousElementSibling){ //New Row?
        row = [];
        results.push(row);
    }
    if(!(this.textContent == '')){
        row.push(this.textContent || this.innerText);            
    }
}); 

要知道某些內容是否未定義,只要與"undefined"進行比較,請使用typeof()。

所以你想做:

if (typeof(this) === "undefined")

你可以添加一個緊湊的方法,如下划線和lodash ...

Array.prototype.compact = function() {
    return this.filter(function(x){
        return x !== undefined;
    });
}

console.log([1,2, '', undefined, 'e', undefined].compact()); // [ 1, 2, '', 'e' ]

您可能應該為compact的本機實現添加一個檢查,因為您用此覆蓋了本機原型。

要不就

暫無
暫無

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

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