gpt4 book ai didi

javascript - 不计算 array.length 中的空值

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:05 25 4
gpt4 key购买 nike

我有问题,我想获取模型的长度,但它始终等于 2。

如果我显示我的 modelFriend.lenght 我有这个:[Thu Jul 06 2017 00:00:00 GMT+0200,null]

null 被视为一个值,因此 length 等于 2。

如果我选择一个日期,如何计算 modelFriend.lenght = 1 的实际大小,如果我选择 2 个日期,如何计算 modelFriend.lenght = 2

这是我的代码:

public selectDate = (date) => {
if (this.mode === 'period') {
const dates = this._modelFriend ? [this._modelFriend[0], this._modelFriend[1]] : [null, null]

if (!dates[0] || dates[1]) {
dates[0] = date
dates[1] = null
} else {
dates[1] = date
}
this._modelFriend = dates
if (this._modelFriend.length === 2 ) {

this.model = dates

}

最佳答案

您可以使用下面这个函数,它使用 filter ,计算数组中的非空元素:

function countNonEmpty(array) {
return array.filter(Boolean).length;
}

var array = [new Date(), null];
console.log(countNonEmpty(array));

关于javascript - 不计算 array.length 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com