如何检查数据是否已经在 javascript 中的数组中?

How to check if data is already in array in javascript?

我正在使用 Bing-Maps API 进行 JavaScript 项目。该项目的目标是搜索用户所在区域的企业,然后在屏幕上打印他们的名称和 phone 号码。 Bing 每个特定区域的搜索限制为 25 次,因此我必须不断移动目标方块以便获得新结果。问题是,目标方块经常重叠,并且网站将之前已经添加的相同业务添加到数组中。我尝试使用几乎每个 javascript 函数来检查数组中的重复项,但无论如何,它一直在向数组中添加重复项,并且没有什么可以阻止它。

function GeocodeCallback(response) {
  var output = document.getElementById('output');
  let used = [] //Array for posted numbers

  //Chech if phone number has been already posted
  function HasDuplicate(object) {
    for (let i = 0; i < used.length; i++) {
      if (used[i] == object) {
        return true
      }
    }
    return false
  }

  if (response &&
    response.resourceSets &&
    response.resourceSets.length > 0 &&
    response.resourceSets[0].resources) {

    var results = response.resourceSets[0].resources;

    let html = ['<table>'];
    //PROBLEM AREA ----------------------------------------------------------------------------------------
    for (var i = 0; i < results.length; i++) {
      console.log("Phone " + results[i].PhoneNumber + "Name " + results[i].name)
      if (!HasDuplicate(results[i].PhoneNumber)) {
        console.log("Not Duplicate")
        html.push('<tr><td>' + results[i].name + '</td><td>' + results[i].PhoneNumber + '</td></tr>'); //<td>', results[i].Website, '</td>
        data += results[i].PhoneNumber + " , " + results[i].name + "\n" //Save Data into file
        used.push(results[i].PhoneNumber)
      } else {
        console.log("IsDuplicate " + results[i].name)
      }
    }
    //PROBLEM AREA ----------------------------------------------------------------------------------------
    html.push('</table>');
    output.innerHTML += html.join('');
  } else {
    output.innerHTML = "No results found.";
  }
}

当我 运行 这段代码时,它打印的数字中有 99% 是不重复的,尽管它们是重复的,但是有 1% 的 phone 数字被标记为重复并且不会添加到数组中。所以我的代码能够检测它是否重复,但由于某种原因它并没有在 100% 的时间内检测到它。我检查有误还是 Bing 地图数据有问题?

如果您想尝试重现该问题,这是我的完整代码。感谢您花时间阅读本文 post,我们将不胜感激。

var map, searchManager;
var BingMapsKey = 'AuV6Kc6hF3yFNL_DXFTDGuSu9DCdIK8zYF208z0eNdqbXtt87UHslIKJ70900Wbj';
let data = "" //String to store data that will be saved 
let userLat, userLong, updatedLat, updatedLong

function GetMap() {
  map = new Microsoft.Maps.Map('#myMap', {
    credentials: BingMapsKey
  });

  //Load the spatial math module
  Microsoft.Maps.loadModule("Microsoft.Maps.SpatialMath", function() {
    //Request the user's location
    navigator.geolocation.getCurrentPosition(function(position) {
      var loc = new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude);
      userLat = position.coords.latitude
      userLong = position.coords.longitude
      updatedLat = userLat + 0.05
      updatedLong = userLong + 0.05
      geocode()
      //Create an accuracy circle
      var path = Microsoft.Maps.SpatialMath.getRegularPolygon(loc, position.coords.accuracy, 36, Microsoft.Maps.SpatialMath.Meters);
      var poly = new Microsoft.Maps.Polygon(path);
      map.entities.push(poly);

      //Add a pushpin at the user's location.
      var pin = new Microsoft.Maps.Pushpin(loc);
      map.entities.push(pin);

      //Center the map on the user's location.
      map.setView({
        center: loc,
        zoom: 17
      });
    });
  });
}



function geocode() {
  var query = document.getElementById('input').value;

  //Move around the map and get locations from specific square
  for (let x = 0; x < 10; x++) {
    const longlat = [userLat, userLong, updatedLat, updatedLong]
    var geocodeRequest = "http://dev.virtualearth.net/REST/v1/LocalSearch/?query=" + encodeURIComponent(query) + "&userMapView=" + encodeURIComponent(longlat) + "&maxResults=25&jsonp=GeocodeCallback&key=" + BingMapsKey;
    CallRestService(geocodeRequest, GeocodeCallback);
    userLat += 0.05
    userLong += 0.05
    updatedLat += 0.05
    updatedLong += 0.05
  }
}

function GeocodeCallback(response) {
  var output = document.getElementById('output');
  let used = [] //Array for posted numbers

  //Chech if phone number has been already posted
  function HasDuplicate(object) {
    for (let i = 0; i < used.length; i++) {
      if (used[i] == object) {
        return true
      }
    }
    return false
  }

  if (response &&
    response.resourceSets &&
    response.resourceSets.length > 0 &&
    response.resourceSets[0].resources) {

    var results = response.resourceSets[0].resources;

    let html = ['<table>'];
    //PROBLEM AREA ----------------------------------------------------------------------------------------
    for (var i = 0; i < results.length; i++) {
      console.log("Phone " + results[i].PhoneNumber + "Name " + results[i].name)
      if (!HasDuplicate(results[i].PhoneNumber)) {
        console.log("Not Duplicate")
        html.push('<tr><td>' + results[i].name + '</td><td>' + results[i].PhoneNumber + '</td></tr>'); //<td>', results[i].Website, '</td>
        data += results[i].PhoneNumber + " , " + results[i].name + "\n" //Save Data into file
        used.push(results[i].PhoneNumber)
      } else {
        console.log("IsDuplicate " + results[i].name)
      }
    }
    //PROBLEM AREA ----------------------------------------------------------------------------------------

    html.push('</table>');


    output.innerHTML += html.join('');


  } else {
    output.innerHTML = "No results found.";
  }
}

let WriteToFile = () => {

  // Convert the text to BLOB.
  const textToBLOB = new Blob([data], {
    type: 'text/plain'
  });
  const sFileName = 'formData.txt'; // The file to save the data.

  let newLink = document.createElement("a");
  newLink.download = sFileName;

  if (window.webkitURL != null) {
    newLink.href = window.webkitURL.createObjectURL(textToBLOB);
  } else {
    newLink.href = window.URL.createObjectURL(textToBLOB);
    newLink.style.display = "none";
    document.body.appendChild(newLink);
  }

  newLink.click();
}

function CallRestService(request) {
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", request);
  document.body.appendChild(script);
}
#myMap {
  width: 600px;
  height: 600px;
  position: relative;
  margin: auto;
  width: 60%;
  padding: 10px;
}

#center {
  margin: auto;
  width: 60%;
  padding: 10px;
}

#search,
#output {
  margin-left: 20%;
}

.form-control {
  margin: 0 20%;
}

#space {
  margin-left: 17%;
}
<!DOCTYPE html>
<html>

<head>
  <title>Business Search</title>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  <script src="script.js"></script>
  <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer></script>
</head>

<body>
  <div id="myMap"></div>

  <h1 class="display-4" id="center">Search for business: </h1>

  <div class="input-group mb-3">
    <input type="text" id="input" class="form-control" value="car">
  </div>

  <button type="button" class="btn btn-outline-dark btn-large" id="search" value="Search" onClick="geocode()">Search</button>
  <button type="button" class="btn btn-outline-dark btn-large" value="Save" onClick="WriteToFile()">Save</button>

  <div id="output">Name<span id="space">Phone Number</span></div>
</body>

</html>

每次单独执行您的请求时,都会重复初始化用于跟踪重复项的数组。

function GeocodeCallback(response) {
  var output = document.getElementById('output');
  let used = [] //<------ This is initialized every time a new result set is arrived
  ...

这意味着它不会跟踪多个呼叫中的重复项 - 因为它总是会丢失上一个呼叫的号码。

数组应该在回调之外定义:

let used = [] //Array for posted numbers

function GeocodeCallback(response) {
  var output = document.getElementById('output');
   ...