簡體   English   中英

如何從項目列表中刪除未定義?

[英]How to remove undefined from a list of items?

如何防止在 output 中出現undefined

var item1 = $(result).find('.item:nth-child(2) a').html(),
    item2 = $(result).find('.item:nth-child(3) a').html(),
    item3 = $(result).find('.item:nth-child(4) a').html(),
    item4 = $(result).find('.item:nth-child(5) a').html();

$('div').html(item1+item2+item3+item4);
var item1 = $(result).find('.item:nth-child(2) a').html(),
item2 = $(result).find('.item:nth-child(3) a').html(),
item3 = $(result).find('.item:nth-child(4) a').html(),
item4 = $(result).find('.item:nth-child(5) a').html();

item1 = typeof item1 === 'undefined' ? '' : item1;
item2 = typeof item2 === 'undefined' ? '' : item2;
item3 = typeof item3 === 'undefined' ? '' : item3;
item4 = typeof item4 === 'undefined' ? '' : item4;

$('div').html(item1+item2+item3+item4);

您可以使用Nullish 合並運算符設置默認值,以防止代碼中出現undefined的值:

const item = undefined ?? "";
//output: ""

或者您可以過濾它們:

const items = [undefined, "Hello", undefined, " World!"];
const filtereditems = items.filter(x=>x); 

const joindItems= filtereditems.join(""); 
//output: 'Hello World!'

您可以將它們全部放在一個數組中,然后對其進行過濾。

const array = [item1, item2, item3, item4];
const onlyDefined = array.filter(item => item !== undefined);

如果你沒有對變量做任何其他事情,你也可以通過循環數字 2 到 5 來分塊完成。

最簡單最干凈的方法)

array.filter(Boolean)

暫無
暫無

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

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