2012-01-27 111 views
0

我试图在JavaScript中使用对象存储用户ID(键)和GPS坐标数组,但由于某种原因每次添加一组新坐标时(何时它从数据库中拉出来),它会覆盖数组(值)中的前一个坐标而不是追加。JavaScript中的对象覆盖键值对

$(function() { 
     $(document).ready(function(){ 
      setInterval(function(){ 
       $.ajax({          
        url: 'api.php',     //the script to call to get data   
        data: "",       
        dataType: 'json',    //data format  
        success: function(data){   //on recieve of reply       
         var loc = {}; 

         user_id = data[0]; 
         lati = data[1];    //get id 
         longi = data[2];   //get name 

         var myLatlngt = 'new google.maps.LatLng(' + lati + ',' + longi + ')'; 

         if (typeof loc[user_id] === 'undefined') { 
          loc[user_id] = []; 
          } 

         loc[user_id].push(myLatlngt); 
         console.log('loc :::', loc); 

这里的日志:

Resource interpreted as Other but transferred with MIME type undefined. 
map2.php:50loc ::: Object  
    86ad04fb-1da5-4118-8b00-942676d62387: Array[1] 
     0: "new google.maps.LatLng(51,-82)" 
     length: 1 
    __proto__: Array[0] 
__proto__: Object 

长数(86ad04 ...)是用户ID(密钥),但如果我把新坐标它将覆盖,而不是附加。我将不胜感激任何帮助。

感谢

回答

2

因为你每次进入该功能时清空loc

var loc = {}; 
+0

我知道这会很简单。感谢您及时的回复! – mkyong 2012-01-27 10:36:05

+0

不客气;-) – 2012-01-27 10:36:28

0

您需要将var loc = {};以外的Ajax回调,使得其状态保存在多个Ajax请求。