我有一个二维数组,是用 jQuery 从 html 表生成的,但有些值是空的,所以""
被展示。
如何删除空值?
<table>
<tr>
<th>1A</th>
<th>1B</th>
<th>1C</th>
</tr>
<tr>
<td>2A</td>
<td>2B</td>
<td>2C</td>
</tr>
<tr>
<td></td>
<td>3B</td>
<td>3C</td>
</tr>
<tr>
<td></td>
<td></td>
<td>4C</td>
</tr>
</table>
<script>
var columns = $('tr').first().children().map(function(i) {
return [
$('tr').map(function(){
return $(this).children().eq(i).text()
}).get()
]
}).get();
<script>
我已经尝试过以下代码:
for( var i = 0; i < columns[0].length; i++){
if ( columns[0][i] === "") {
columns[0].splice(i, 1);
}
}
它适用于某些空值,但并非所有空值都因某种原因被删除。
Output: https://i.stack.imgur.com/LvMSt.jpg https://i.stack.imgur.com/LvMSt.jpg
您可以使用如下过滤器:
arr = arr.filter(item => item);
Example:
let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);
// Result
// ['One', 'Two', 'Four']
因为空字符串的计算结果为布尔值false
。
它适用于所有虚假值,例如0
, false
, null
, undefined
, ''
, etc.
如果你想保留一些值,比如数字0
(零)你可以使用item !== undefined
。这仅过滤未定义的值。请记住修剪字符串或使用正则表达式检查以确保空字符串没有空格。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)