首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查javascript中的数据是否已经在数组中?

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

Stack Overflow用户
提问于 2021-07-29 17:50:39
回答 1查看 131关注 0票数 0

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

代码语言: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%的电话号码被标记为重复的,并且没有添加到数组中。所以我的代码能够检测到它是否是复制的,但由于某种原因,它不会100%地做到这一点。我是做错了检查还是必应地图数据出了问题?

这是我的完整代码,如果您想要复制这个问题。感谢您花时间阅读这篇文章,如有任何帮助将不胜感激。

代码语言:javascript
运行
复制
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);
}
代码语言:javascript
运行
复制
#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%;
}
代码语言:javascript
运行
复制
<!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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-29 18:13:46

用于跟踪重复项的数组将在每次单独执行请求时重复初始化。

代码语言:javascript
运行
复制
function GeocodeCallback(response) {
  var output = document.getElementById('output');
  let used = [] //<------ This is initialized every time a new result set is arrived
  ...

这意味着它不会跟踪跨多个调用的重复,因为它总是丢失前一个调用的号码。

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

代码语言:javascript
运行
复制
let used = [] //Array for posted numbers

function GeocodeCallback(response) {
  var output = document.getElementById('output');
   ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68580740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档