2017-07-12 24 views
1

空值我有問題,我想我的模型的長度,但總是等於2不要指望在array.lenght

如果我顯示我modelFriend.lenght我有這樣的:[Thu Jul 06 2017 00:00:00 GMT+0200,null]

null正在考慮類似的值,因此length等於2

怎麼能算真正的大小是modelFriend.lenght = 1如果我選擇一個日期和modelFriend.lenght = 2如果我選擇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 

    } 
+0

那麼最初避免使用null值是不是正確?目前的做法似乎有點不對我。 –

+0

確定你的解決方案是什麼,因爲它用於驗證測試 如果用戶只輸入一個日期是錯誤的,所以ng-無效,但如果他選擇了一個是ng-有效的時間段 所以我想測試我的數組長度是例如2 你將如何進行? – ouanounou

回答

1

您可以使用下面這個功能,它採用filter,計算從數組中的非空元素:

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

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

+0

感謝回覆,但如何可以在我的代碼中使用這個我現在不是如何可以實現, 對不起,我是初學者... – ouanounou

+0

您可以將'this._modelFriend.length === 2'替換爲'countNonEmpty(this._modelFriend)=== 2'' –

+0

或者,如果你不想創建那個函數(countNonEmpty),你可以直接使用它:'this._modelFriend.filter(Boolean).length === 2 ' –

0

我假定在你的情況下數組的長度總是2。這就是爲什麼我只是要檢查this._modelFriend[0]!=null && this._modelFriend[1]!=null,而不是進行篩選並檢查新過濾數組的長度。如果表達式的計算結果爲true,那麼您有2個日期。

其他一切都很複雜,更難以閱讀和開銷。

+0

結果是相同的,如果我評估this._modelFriend.filter(布爾).length === 2 或如果我評估this._modelFriend [0]!= null && this。 _modelFriend [1]!= null 結果是真是假? – ouanounou

+0

是的,它是一樣的。 使用過濾器的方法是有意義的,如果有問題的數組將通過動態的長度。因爲它總是有2的長度,所以肯定是一個開銷。 –

+0

好的,我明白謝謝你的建議,我會遵循它 – ouanounou