javascript - 为什么我不能将这些附加数据推送到我的数组中?

标签 javascript jquery arrays

我正在进行 API 调用,这是响应

enter image description here

如您所见,键 0 和 1 的“outcome_status”为 NULL,而键 2 已填充。 返回结果的数量是动态的

我希望循环结果并将“类别”和“位置”详细信息插入数组中,如果“outcome_status”不为 NULL,那么我希望将该数据添加到同一数组中。

问题是,在检查 Outout_status 是否为 null 的 IF 语句中,我无法将 forloop var i; 变量分配为 我第二次使用.push()的mapData。

line:68 Uncaught TypeError: Cannot read property 'push' of undefined

var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {      

编辑:我想这样做。

            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]); 

但是如果没有 outcome_status 那么它将失败......所以我将第二部分添加到条件中

         if(data[i].outcome_status != null) { 

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise 
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });

最佳答案

一些问题:

  • 您的 for 循环以 i 等于 1 开始,因此即使在第一次推送之后,mapData[i] 还不存在,因此应用 push 是没有意义的。
  • 如果您想要push其他元​​素到现有数组中,则不应将这些其他元素添加为数组的一部分,而应将它们作为单独的参数提供给push .

此外,当使用像 map 这样的数组方法时,代码会变得更加实用。

以下是填充 mapDataheatmapData 的部分:

// Create a new array, with nested arrays: one per data item
mapData = data.map(function (item) {
    // Use a local variable to build the sub-array:
    var arr = [
      item.category,
      item.location.street.name,
    ];
    if (item.outcome_status) { // add 2 more elements if they exist
        arr.push( // note: no square brackets here
            item.outcome_status.category,
            item.outcome_status.date,
        );
    }
    // Add it to `dataMap` by returning it to the `map` callback:
    return arr;
});

// Extend the heatmap with additional locations
heatmapData = heatmapData.concat(data.map(function (item) {
    return new google.maps.LatLng(item.location.latitude,item.location.longitude);
}));

关于javascript - 为什么我不能将这些附加数据推送到我的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44438133/

相关文章:

javascript - 如果我在 div 中放置文本动画效果,我的后续 div 背景不会显示

jquery - 当我将鼠标悬停在图像或链接上时使文本淡入

arrays - 试图添加到 slice 的索引超出范围

arrays - 在 Apple Swift 中将 json 转换为数组的字符串数组

jquery - diff 不是函数

javascript - 按年份分组对象数组

javascript - 在 CSS 转换上卡顿

javascript - 选中复选框时如何显示和隐藏 id

javascript - 脚本无法放置在正文标记中

javascript - 如何搜索 JSON 并查找特定名称的每次出现(带增量)