JavaScript检查数组中的重复输入和至少一个字母
问题描述:
当我点击一个按钮时,我想创建一个条目。这个条目有一个标题和一个文本。在创建新条目之前,应该检查,如果该标题已经存在,并且该标题为空。检查空是很重要的,因为文本可能不是“”(空格),这应该至少有一个数字/字母或数字。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;
}
有人能帮助我在这里?
答
使用Array#some
和trim
:
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
答
我会修改这个功能
function checkTitleInput(inputText) {
inputText = inputText.trim();
if (inputText.length > 0 && entries.filter(entry=>entry.title.equals(inputText)).length==0)
return true;
return false;
}
没有它是对象的数组。像entry1,entry2,entry3,...所以我会写'var title2 = entry2.title;' – peterHasemann
'const checkTitleInput = text => !! text.trim()&&!entries.includes(text.trim()) ;' – Thomas