[英]How to remove undefined from a list of items?
How to prevent appearing undefined
in the output?如何防止在 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);
You can use Nullish coalescing operator to set a default value to prevent undefined
values in your code:您可以使用Nullish 合并运算符设置默认值,以防止代码中出现
undefined
的值:
const item = undefined ?? "";
//output: ""
or You can filter them:或者您可以过滤它们:
const items = [undefined, "Hello", undefined, " World!"];
const filtereditems = items.filter(x=>x);
const joindItems= filtereditems.join("");
//output: 'Hello World!'
You could put them all in an array and then filter it.您可以将它们全部放在一个数组中,然后对其进行过滤。
const array = [item1, item2, item3, item4];
const onlyDefined = array.filter(item => item !== undefined);
If you're not doing anything else with the variables, you could also do it all in chunk, by looping over the numbers 2 through 5.如果你没有对变量做任何其他事情,你也可以通过循环数字 2 到 5 来分块完成。
Easiest and cleanest way )最简单最干净的方法)
array.filter(Boolean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.