我将从URL获得的数据添加到数组作物中。在此之后,我将在新数组cropsSoFar的帮助下检查重复的作物。

     var crops=[];

     for(int i=0; i<results.length;i++)
     {
         var terrains= results.features[i].attributes.Terrain_Id;
        var rawDataOfTerrain=getjsondata("http://or.org");

         var trsetdata= jQuery.parseJSON(tersetjson).d.results;

         crops.push(trsetdata);
     }

         var cropsSoFar= [];

         for(int i=0; i<crops.length;i++)
         {
             var crop= crops[i];
             if(crop in cropsSoFar)
             {
                 crops.pop(crop);
             }
             cropsSoFar.push(crops[i]);

         }

         if(crops.length!=1)
             alert("Please select terrains with the same crop");


这是在数组中搜索字符串的正确方法吗?如果是这样,有没有更简单的方法?如果没有,我哪里出问题了?

最佳答案

您可以在使用crops首次创建indexOf时检查重复项。

var crops = [];

for( int i = 0; i < results.length; i++ ) {
    var terrains = results.features[i].attributes.Terrain_Id;
    var rawDataOfTerrain =getjsondata("http://or.org");
    var trsetdata = $.parseJSON(tersetjson).d.results;

    if( crops.indexOf(trsetdata) === -1 )
        crops.push(trsetdata);
 }

 if( crops.length != 1 )
      alert("Please select terrains with the same crop");

09-26 03:24