繁体   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