简体   繁体   English

避免 JavaScript 中的重复

[英]Avoid duplication in JavaScript way

I would like to prevent for adding duplicate values.我想防止添加重复值。

if (this.sQuestions.findIndex((item) => 
    item.question.replace(/\s/g, "").toLowerCase() ===  
        this.quest.replace(/\s/g, "").toLowerCase()) > 0) 
{
  this.isQuestionExist = true;
}
else {
  //save function
}

It's working except the sQuestions[0] element, Why?.除了sQuestions[0]元素,为什么?

I suggest to use Set for this purpose.我建议为此使用Set As the documentation states:正如文档所述:

The Set object lets you store unique values of any type, whether primitive values or object references. Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。

Example from the documentation:文档中的示例:

 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

I hope this helps!我希望这有帮助!

You are comparing against > 0 if the item is not found in the array, the function will return -1 so it should be compared against -1如果在数组中找不到该项目,则您正在与> 0进行比较,该函数将返回-1因此应与-1进行比较

This will be working.这将起作用。

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)

For performance and clarity reasons you should index your questions in a dedicated structure like a Map :出于性能和清晰度的原因,您应该在专用结构(如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)

Result:结果:

{ ID: 2, text: 'Where is it?' }
undefined

You can use some method to check whether the data is existing in your array:您可以使用some方法来检查数据是否存在于您的数组中:

if (!this.sQuestions.some(q => q.question == newQuestion)) 
{
  this.isQuestionExist = true;
}
else {
  //save function
}

An example:一个例子:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM