简体   繁体   English

检查数组元素是否已经存在

[英]Check to see if an array element already exists

I have implemented function to add a name to an array which then will be displayed into a table on a page.我已经实现了将名称添加到数组中的功能,然后该名称将显示在页面上的表格中。

The next question I have is, how do I check whether a first and last name already exist in the array.我的下一个问题是,如何检查数组中是否已经存在名字和姓氏。 My function is below, once I know how to handle the check I will add it to the function.我的函数在下面,一旦我知道如何处理检查,我会将其添加到函数中。

function addNewGuest(event) {
    event.preventDefault()
    let f = document.querySelector("#first_name").value
    let l = document.querySelector("#last_name").value
    let names = getGuestList()

    if (f || l) {
        alert("First and Last name required.")
    }
    
    if (f && l) {
        let name = { fName: f, lName: l }
        names.push(name)
        localStorage.setItem('names', JSON.stringify(names))
    }
    displayGuestList()
    document.querySelector("#first_name").value = ''
    document.querySelector("#last_name").value = ''
}

使用Array.prototype.find搜索一个人,如果find方法返回undefined ,则该人不存在,所以我们翻转为布尔值。

const alreadyExists = names.find(({fName, lName}) => fName === f && lName === l) !== undefined;

You would have to loop over the array and check each element to make sure it exists.您必须遍历数组并检查每个元素以确保它存在。

An easy way to do so would be to use the some helper function on arrays.一个简单的方法是在数组上使用一些辅助函数。

// check if a name with the same first and last name already exists
function nameExists(input, namesList) {
  return namesList.some(name => (input.f === name.f) && (input.l === name.l);
}

However, looping over each item is pretty inefficient for very large datasets so you may be better off looking into using data structures like a Set or even a regular object which are tailored for looking up key/value pairs.但是,对于非常大的数据集,循环遍历每个项目的效率非常低,因此您最好研究使用像Set这样的数据结构,甚至是为查找键/值对而定制的常规对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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