2017-06-16 77 views
0

當我點擊一個按鈕時,我想創建一個條目。這個條目有一個標題和一個文本。在創建新條目之前,應該檢查,如果該標題已經存在,並且該標題爲空。檢查空是很重要的,因爲文本可能不是「」(空格),這應該至少有一個數字/字母或數字。JavaScript檢查數組中的重複輸入和至少一個字母

所以這是我走到這一步:

var entries = store.getEntries(); // the entry list. Each entry has the property "title" 

    function checkTitleInput(inputText) { // check the titleInput before creating a new entry 

     if (inputText.length > 0 && // field is empty? 
     /* at least 1 letter */ && // not just a whitespace in it? 
     /* no duplicate */ // no duplicate in the entry list? 
    ) 
     return true; 

     return false; 
    } 

有人能幫助我在這裏?

+0

沒有它是對象的數組。像entry1,entry2,entry3,...所以我會寫'var title2 = entry2.title;' – peterHasemann

+0

'const checkTitleInput = text => !! text.trim()&&!entries.includes(text.trim()) ;' – Thomas

回答

2

使用Array#sometrim

function checkTitleInput (inputText) { 
    var trimmed = inputText.trim(); 
    var exists = entries.some((entry) => entry.title === trimmed); 
    return trimmed.length > 0 && !exists; 
} 

你可以使它更短:

function checkTitleInput (inputText) { 
    var trimmed = inputText.trim(); 
    return !!trimmed && !entries.some((entry) => entry.title === trimmed); 
} 
+0

謝謝,這有助於很多:) – peterHasemann

2

我會修改這個功能

function checkTitleInput(inputText) { 
inputText = inputText.trim(); 
if (inputText.length > 0 && entries.filter(entry=>entry.title.equals(inputText)).length==0) 
     return true; 
return false; 
} 
相關問題