[英]Avoid duplication in JavaScript way
我想防止添加重复值。
if (this.sQuestions.findIndex((item) =>
item.question.replace(/\s/g, "").toLowerCase() ===
this.quest.replace(/\s/g, "").toLowerCase()) > 0)
{
this.isQuestionExist = true;
}
else {
//save function
}
除了sQuestions[0]
元素,为什么?
我建议为此使用Set
。 正如文档所述:
Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。
文档中的示例:
const set1 = new Set([1, 2, 3, 4, 5]); console.log(set1.has(1)); // expected output: true console.log(set1.has(5)); // expected output: true console.log(set1.has(6)); // expected output: false
我希望这有帮助!
如果在数组中找不到该项目,则您正在与> 0
进行比较,该函数将返回-1
因此应与-1
进行比较
这将起作用。
if (this.sQuestions.findIndex((item) => item.question.replace(/\s/g, "").toLowerCase() === this.quest.replace(/\s/g, "").toLowerCase()) !== -1) {
this.isQuestionExist = true;
}
else {
//save function
}
根据你的问题,你可以试试
let uniqueQuestions = new Set(this.sQuestions)
出于性能和清晰度的原因,您应该在专用结构(如Map
索引您的问题:
function getKey(question)
{
return question.replace(/\s/g, '').toLowerCase()
}
var question1 = {
ID: 1,
text: 'What time is it?'
}
var question2 = {
ID: 2,
text: 'Where is it?'
}
var question3 = {
ID: 3,
text: 'What is it?'
}
var questions = new Map()
questions.set(getKey(question1.text), question1)
questions.set(getKey(question2.text), question2)
questions.set(getKey(question3.text), question3)
var quest = 'Where is it?'
var match = questions.get(getKey(quest))
console.log(match)
quest = 'WTF?'
match = questions.get(getKey(quest))
console.log(match)
结果:
{ ID: 2, text: 'Where is it?' }
undefined
您可以使用some
方法来检查数据是否存在于您的数组中:
if (!this.sQuestions.some(q => q.question == newQuestion))
{
this.isQuestionExist = true;
}
else {
//save function
}
一个例子:
let arr = [1, 2, 3, 4, 5]; console.log(`arr has 1`, arr.some(s=> s == 1)) console.log(`arr has 10`, arr.some(s=> s == 10)) console.log(`arr has 1`, arr.some(s=> s == 6))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.