当我点击一个按钮时,我想创建一个条目。该条目有标题和文本。在创建新条目之前,应该检查该标题是否已存在以及该标题是否为空。检查是否为空很重要,因为文本可能不是“”(空格),它至少应该有一个数字/字母或数字。
这就是我到目前为止得到的:
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);
}
关于JavaScript 检查数组中是否存在重复输入以及至少一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588989/