避免以 JavaScript 方式重复



我想防止添加重复值。

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))

最新更新