簡體   English   中英

避免 JavaScript 中的重復

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM